What Are Sealed Classes in Java?
The final
modifier can be considered a strong form of sealing, where extension/implementation is prohibited completely.
Conceptually: final
= sealed
+ an empty permits
clause.
Unlike final
which completely prohibits extension/implementation.
A Sealed
class
/interface
restrict which other classes or interfaces may extend or implement them.
History
- Sealed Classes were proposed by JEP 360 and delivered in JDK 15 as a
preview feature.
- They were proposed again, with refinements, by JEP 397 and delivered
in JDK 16 as a preview feature.
- This JEP proposes to finalize Sealed
Classes in JDK 17, with no changes from JDK 16.
Goals
Description
A class/interface is sealed by applying the sealed
modifier to its declaration.
Then, after any extends and implements clauses, the permits
clause specifies the classes that are permitted to extend the sealed class.
Example
For example, the following declaration of Loan
specifies permitted UnsecuredLoan
, SecuredLoan
subclasses:
sealed interface Loan permits UnsecuredLoan,SecuredLoan{}
final class UnsecuredLoan implements Loan {}
record SecuredLoan() implements Loan{}
Benefits Of Sealed Class With Pattern Matching
Using Pattern Matching, instead of inspecting an instance of a sealed class with if-else chains, we can use a switch
enhanced with type test patterns.
This will allow the Java compiler to check all the permitted classes are covered for us.
For example, consider this code:
void checkLoanType(Loan loan) {
if (loan instanceof UnsecuredLoan unsecuredLoan) {
// something
} else if (loan instanceof SecuredLoan securedLoan) {
// something
}
}
The Java compiler cannot ensure that the instanceof tests cover all the permitted subclasses of Loan. Thus, no compile-time error message would be issued if any instanceof Loan was omitted.
In contrast, using a pattern matching switch
expression, the compiler can confirm that every permitted subclass of Loan is covered. The compiler will, moreover, issue an error message if any of the cases are missing:
void checkLoanType(Loan loan) {
switch (loan) {
case SecuredLoan securedLoan -> {} //generated by compiler.
case UnsecuredLoan unsecuredLoan -> {} //generated by compiler.
}
}
Reference:
JEP 360: Sealed Classes
sealed
classes.