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.

--

--

Swathi Prasad

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