Sealed classes or interfaces in Java
Fine-grained control over inheritance.
Sealed classes and interfaces were introduced in Java (previewed in Java 15, standardized in Java 17) primarily to give developers explicit control over inheritance and to provide a crucial foundation for pattern matching.
Before sealed classes, a class’s inheritance was either:
- Completely open: Any class could extend it (unless it was in a different package and had package-private constructors).
- Completely closed: Using the
finalkeyword, no class could extend it.
This “all or nothing” approach was problematic. Sealed classes provide a powerful middle ground.
Here are the main reasons for their introduction:
1. To Control and Restrict Inheritance
The most direct benefit is to allow the author of a class or interface to state exactly which other classes or interfaces are permitted to extend or implement it.
Get Kandaanusha’s stories in your inbox
Join Medium for free to get updates from this writer.
This is done using the sealed and permits keywords:
// Only Circle, Square, and Triangle can extend Shape
public sealed class Shape permits Circle, Square, Triangle {
// ...
}
// These permitted subclasses MUST be defined
public final class Circle extends Shape { /* ... */ }
public final class Square extends Shape { /* ... */ }
public non-sealed class Triangle extends Shape { /* ... */ }A permitted subclass must declare itself as one of three types:
final: It cannot be extended further (likeCircleandSquare).sealed: It can be extended, but only by its own permitted list of subclasses.non-sealed: It reverts to the old behavior and can be extended by any class (likeTriangle).
2. To Improve Domain Modeling
Often, you want to model a concept that has a fixed set of variations. For example:
- A
Shapein a drawing app might only be aCircle,Square, orRectangle. - An
Optionin functional programming is eitherSome(value)orNone. - A JSON value is either an
JsonObject,JsonArray,JsonString,JsonNumber,JsonBoolean, orJsonNull
Sealed classes allow you to model these “closed” hierarchies perfectly. You are explicitly stating that Shape only exists as these specific subtypes, preventing other developers from adding an "Octagon" and breaking your logic.
3. To Enable Exhaustive Pattern Matching
This is the most significant long-term goal. Sealed classes are a key feature for enabling Pattern Matching for switch (JEP 441, finalized in Java 21).
Because the compiler knows the complete, fixed set of all possible subtypes of a sealed class, it can perform exhaustive checks at compile time. This means you no longer need a default clause in your switch, and the compiler will give you an error if you forget to handle one of the permitted types.
Before Sealed Classes (and Pattern Matching):
// Old, verbose, and error-prone
double getArea(Shape shape) {
if (shape instanceof Circle) {
Circle c = (Circle) shape;
return Math.PI * c.radius() * c.radius();
} else if (shape instanceof Square) {
Square s = (Square) shape;
return s.side() * s.side();
} else if (shape instanceof Triangle) {
Triangle t = (Triangle) shape;
return 0.5 * t.base() * t.height();
} else {
// We need this 'else' just in case someone adds a
// new Shape we don't know about.
throw new IllegalArgumentException("Unknown shape");
}
}With Sealed Classes and Pattern Matching:
// Clean, type-safe, and exhaustive
double getArea(Shape shape) {
// 'Shape' is sealed, so the compiler knows that
// Circle, Square, and Triangle are the ONLY options.
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Square s -> s.side() * s.side();
case Triangle t -> 0.5 * t.base() * t.height();
// No 'default' clause is needed!
};
}If you later add Rectangle to the permits list of Shape, the getArea method will fail to compile until you add a case Rectangle r -> ... handler. This is a massive improvement in code safety and maintainability.





