Java › Interfaces & Abstract Classes
How would you design a sealed interface (Java 17+) to restrict which classes are permitted to implement it, and what benefit does this provide over a traditional open (unrestricted) interface for exhaustiveness checking?
AdvancedAnswer
A sealed interface (declared with the sealed modifier and a permits clause listing the specific classes/interfaces allowed to implement or extend it) restricts implementation to only that explicitly declared, closed set, unlike a traditional open interface which any class anywhere can freely implement -- this restriction is what enables the compiler to perform exhaustiveness checking in a pattern-matching switch expression over the sealed type (verifying at compile time that every possible permitted subtype is handled), a capability that's fundamentally impossible for an open interface, since the compiler could never know the complete universe of possible implementing classes for an unrestricted interface.
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 {}
double area(Shape shape) {
return switch (shape) { // exhaustive, no default needed -- compiler verifies ALL permitted types are covered
case Circle c -> Math.PI * c.radius() * c.radius();
case Square s -> s.side() * s.side();
case Triangle t -> 0.5 * t.base() * t.height();
};
}Real-world example A geometry library seals its Shape interface to exactly three permitted implementations, letting every switch expression operating over Shape throughout the codebase benefit from compile-time exhaustiveness checking, immediately catching (as a compile error) any place where a newly-added fourth shape type was forgotten in an existing switch, a safety net an open, unrestricted interface could never provide.