Sealed classes for type hierarchies
Restrict which classes can extend a type — enabling exhaustive switches.
Porównanie kodu
✕ 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 {}
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
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.
Stare podejście
Open Hierarchy
Nowoczesne podejście
sealed permits
Od JDK
17
Poziom trudności
Średniozaawansowany
Wsparcie JDK
Sealed classes for type hierarchies
Dostępne
Widely available since JDK 17 LTS (Sept 2021)
Jak to działa
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.
Powiązana dokumentacja