Sealed classes for type hierarchies
Home / Language / Sealed classes for type hierarchies
Code Comparison
// Anyone can extend Shape
public abstract class Shape { }
public class Circle extends Shape { }
public class Rect extends Shape { }
// unknown subclasses possible
public sealed interface Shape
permits Circle, Rect {}
public record Circle(double r)
implements Shape {}
public record Rect(double w, double h)
implements Shape {}
Why the modern way wins
๐
Controlled hierarchy
Only permitted subtypes can extend โ no surprise subclasses.
โ
Exhaustive matching
The compiler verifies switch covers all cases, no default needed.
๐
Algebraic data types
Model sum types naturally โ sealed + records = ADTs in Java.
Old Approach
Open Hierarchy
Modern Approach
sealed permits
JDK Support
Sealed classes for type hierarchies
Available
Widely available since JDK 17 LTS (Sept 2021)
How it works
Sealed classes define a closed set of subtypes. The compiler knows all possible cases, enabling exhaustive pattern matching without a default branch. Combined with records, they model algebraic data types.
Related Documentation
Proof