โ— Shell
clean mode source โ†—

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