sealed
sealed Interfaces/Classes
- only permit certain classes to implement the class/interface
- sealed classes/interfaces constraints:
- permitted class should be in same module as the sealed class
- permitted class should explicitly extend the sealed class
- permitted class must define a modifier:
final: class cannot be inherited
sealed: class is sealed
non-sealed: open for extension, other classes can inherit this class
sealed interface Vehicle permits Car, Truck {
// ...
}
// must use `final` or `sealed` or `non-sealed`
final class Truck extends Vehicle {
// ...
}
permits must be used after extends or implements
sealed class Parent extends GrandParent permits Child {
// ...
}
- Although possible, it is not recommended to omit
permits clause.
- If it is omitted then all classes in the same compilation unit can inherit the class