Week 42 — What is a `sealed` class or interface?

Question of the Week #42
What is a sealed class or interface?
2 Replies
Eric McIntyre
Eric McIntyre14mo ago
sealed is a modifier on classes and interfaces that restricts which other classes/interfaces can extend or implement it. If a class or interface is sealed, only "permitted" types can implement/extend it. Permitted subtypes can be specified using the permits keyword.
public sealed interface SomeSealedInterface permits SomeClass, SomeInterface {}
//public class IllegalClass implements SomeSealedInterface {} // compile-time error since SomeSealedInterface does not permit IllegalClass
public sealed interface SomeSealedInterface permits SomeClass, SomeInterface {}
//public class IllegalClass implements SomeSealedInterface {} // compile-time error since SomeSealedInterface does not permit IllegalClass
Types extending a sealed class or implementing a sealed interfaces must either be final, sealed or non-sealed. In case of a non-sealed class or interface, it can be extended like any other type that isn't sealed.
public non-sealed interface SomeInterface extends SomeSealedInterface {}
public sealed class SomeClass implements SomeSealedInterface permits SomeFinalSubclass, SomeNonSealedSubclass {}
public final class SomeFinalSubclass extends SomeClass {}
public non-sealed class SomeNonSealedSubclass extends SomeClass {}
public non-sealed interface SomeInterface extends SomeSealedInterface {}
public sealed class SomeClass implements SomeSealedInterface permits SomeFinalSubclass, SomeNonSealedSubclass {}
public final class SomeFinalSubclass extends SomeClass {}
public non-sealed class SomeNonSealedSubclass extends SomeClass {}
📖 Sample answer from dan1st
Eric McIntyre
Eric McIntyre14mo ago
Sealed keywords specifies the allowed inheritance targets of a class or an interface. The types not in the permited list will not be able to inherit it.
Submission from kaisinel
Want results from more Discord servers?
Add your server