Sealed classes
A sealed class is a constraint that permits only given classes to implement it. These permitted classes must explicitly extend the sealed class and also have one of the sealed
, non-sealed
, or final
modifiers. The feature is delivered as of java 17 (JEP 409) and was available as a preview longer before (Java 15).
sealed interface IdentificationDocument permits IdCard, Passport, DrivingLicence { }
final class IdCard implements IdentificationDocument { }
final class Passport implements IdentificationDocument { }
non-sealed class DrivingLicence implements IdentificationDocument { }
class InternationalDrivingPermit extends DrivingLicence {}
Usage with pattern matching
I find this new feature awesome in conjunction with pattern matching introduced as a preview as of Java 17 (JEP 406)!
The permitted class restriction assures all the subclasses are known in compile time. Using the switch
expressions (JEP 361 as of Java 14) the compiler requires either to list all the permitted classes or use the default
keyword for the remaining ones. Consider the following example using the classes above:
final String code = switch(identificationDocument) {
case IdCard idCard -> "I";
case Passport passport -> "P";
};
The compiler upon javac Application.java --enable-preview -source 17
results in an error:
Application.java:9: error: the switch expression does not cover all possible input values
final String code = switch(identificationDocument) {
^
Note: Application.java uses preview features of Java SE 17.
Note: Recompile with -Xlint:preview for details.
1 error
Once all permitted classes or the default
keyword are used, the compilation is successful:
final String code = switch(identificationDocument) {
case IdCard idCard -> "I";
case Passport passport -> "P";
case DrivingLicence drivingLicence -> "D";
};