All topics
library
intermediate

Sealed Classes & Interfaces (Java 17)

Restrict which classes can extend a type — enabling exhaustive pattern matching and controlled hierarchies.

Sealed classes and interfaces (preview in Java 15, stable in Java 17) let you control which classes can extend or implement a type. You declare the permitted subtypes explicitly.

Sealed class = an invitation-only club. Only approved members (permitted subtypes) can join. Everyone else is turned away at the door.

Key Concepts

1
sealed interface Shape permits Circle, Rectangle, Triangle { }
2
Permitted subtypes must be in the same module (or package for unnamed modules) and must declare themselves as: - final — no further extension - sealed — further restricted extension - non-sealed — reopened for unrestricted extension
3
Why sealed matters: 1. Exhaustive pattern matching: the compiler knows all subtypes, so switch can be exhaustive without a default case. This is the killer feature — it enables algebraic data types in Java. 2. API design: clearly communicate which extensions are intended and supported. 3. Security: prevent unauthorized implementations of sensitive interfaces.
4
Sealed classes work beautifully with records (which are implicitly final): sealed interface Shape permits Circle, Rectangle { } record Circle(double radius) implements Shape { } record Rectangle(double w, double h) implements Shape { }
5
Combined with pattern matching switch (Java 21), you get exhaustive, type-safe branching without instanceof chains.