Java 17 sealed classes
Intro
Java 17 is the long-term support release which was released on September 2021. In this article I want to describe sealed classes feature. All examples from this article are available at github repo https://github.com/anton-liauchuk/java-17-features.
Installation
I propose to use SdkMan for installing Java 17. To list possible Java installations:
sdk list java
Choose needed version and install via command:
sdk install java 17.0.3-oracle
For switching between already installed versions:
sdk use java 17.0.3-oracle
Sealed classes
Sealed classes and interfaces restrict which other classes or interfaces may extend or implement them. Let’s check it on practice. For example, we have sealed interface:
public sealed interface Operator permits EqualsOperator, NotEqualsOperator {
}This interface requires you to implement EqualsOperator, NotEqualsOperator:
public final class EqualsOperator implements Operator {
}public final class NotEqualsOperator implements Operator {
}EqualsOperator, NotEqualsOperator must be sealed, non-sealed or final. After adding sealed keyword to child classes, we will have the same situation which was described for Operator and child classes. final - will restrict the inheritance on this level. The interesting part is about non-sealed keyword, it will give the possibility to define child classes, as example:
public non-sealed class NonSealedOperator implements Operator {
}public class ChildOperator extends NonSealedOperator {
}It can be useful for setting up child classes from sealed parent classes.
Record classes are great for using with sealed classes because they are implicitly declared final:
public record RecordOperator() implements Operator {
}Conclusion
Sealed classes - it’s great tool for setting up restrictions for child classes for your framework. The flexibility with non-sealed keyword gives the opportunity to remove this restriction for one branch of your classes.