Introduction to Sealed Classes

Swathi Prasad
2 min readJan 8, 2022

Learn about fine-grained inheritance control in Java

Image from Pixabay

Sealed classes feature was released in Java 17. However it was already available as a preview feature since Java 15 and revised in Java 16.

Sealed classes can restrict other classes or interfaces from extending or implementing them. In short, this feature allows the author to have a control which code is responsible for implementing it.

Earlier, restrictions of super classes were possible only via access modifiers but now there is a declarative way of handling restrictions.

Let’s look at some examples:

public abstract sealed class Car permits Coupe, HatchBack, Sedan {

abstract int getSpeed();
}
public final class Sedan extends Car {

@Override
int getSpeed() {
return 200;
}
}
public final class HatchBack extends Car {

@Override
int getSpeed() {
return 100;
}
}

The class Car is a sealed class which permits only Coupe, HatchBack and Sedan sub-classes to extend it.

A permitted subclass may also be declared sealed or non-sealed. If we declare it non-sealed then it is open for extension.

Let’s define a non-sealed sub-class which extends the class Car.

public non-sealed class Coupe extends Car {

@Override
int getSpeed() {
return 250;
}
}

Now, let’s create another sub-class Van and extend non-sealed class. Notice that we can inherit from the sealed class.

public class Van extends Coupe {

@Override
public int getSpeed() {
return 100;
}

}

Let’s define another class MiniBus that extends sealed class.

public class MiniBus extends Car {

@Override
public int getSpeed() {
return 100;
}
}

It throws a compilation error and you would see an error message similar to the following.

java: class is not allowed to extend sealed class: ..Car (as it is not listed in its permits clause)

Conclusion

Sealed classes can help us create hierarchies in a declarative manner that are more accurate and secure. As soon as a sealed class requirement is violated, the compiler throws an exception, which not only brings benefits during development and testing, but also reduces unpredictable effects.

The complete code can be found on my GitHub repository.

Swathi Prasad

Software architect and developer living in Germany. Sharing my opinion and what I learn.