Language Średniozaawansowany

Restrict which classes can extend a type — enabling exhaustive switches.

✕ 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ć.
🔐

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
Sealed classes for type hierarchies
Dostępne

Widely available since JDK 17 LTS (Sept 2021)

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.

Udostępnij 𝕏 🦋 in