Skip to content
AgileLogics
4 min read

Sealed Classes

Prerequisites: Records

A sealed class or interface (Java 17+) lists exactly which classes are allowed to extend or implement it — closing off the set of subtypes so the compiler can reason about all of them.

sealed interface Shape permits Circle, Square, Triangle {}

record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
record Triangle(double base, double height) implements Shape {}

Paired with pattern matching (next lesson), a switch over a sealed type can be checked exhaustively by the compiler — if a new subtype is added later and a switch doesn't handle it, that switch fails to compile instead of silently misbehaving at runtime.