Sealed classes for type hierarchies
Restrict which classes can extend a type — enabling exhaustive switches.
Code Comparison
✕ Java 8
// Anyone can extend Shape
public abstract class Shape { }
public class Circle extends Shape { }
public class Rect extends Shape { }
// unknown subclasses possible
✓ Java 17+
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
Since JDK
17
Difficulty
intermediate
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.