Sealed class
Sealed classes (stabilised in Java 17) restrict which classes may extend or implement them. The author explicitly lists the allowed subtypes with the permits clause. This enables exhaustive pattern matching and ADT-style domain modelling.
Declaration
public sealed interface Shape permits Circle, Square, Triangle {}
public record Circle(double radius) implements Shape {}
public record Square(double side) implements Shape {}
public record Triangle(double base, double height) implements Shape {}
Exhaustive switch
double area(Shape s) {
return switch (s) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Square sq -> sq.side() * sq.side();
case Triangle t -> 0.5 * t.base() * t.height();
// no default β compiler verifies exhaustiveness
};
}
sealed, non-sealed, final
A direct subtype of a sealed type must declare itself as:
finalβ cannot be extended further (typical for records).sealedβ can only be extended by its own permits list.non-sealedβ re-opens the hierarchy to arbitrary subtypes.
Why it matters
Sealed types let the compiler (and human readers) know the complete set of subtypes. Combined with pattern matching in switch, you get exhaustive, refactor-safe dispatch β the compiler flags missing cases when you add a new subtype.