Video in progress
Do sealed interfaces and pattern matching `switch` replace classic polymorphism?
Not entirely; they extend along a different axis. With polymorphism, adding a new type is easy and a new operation is hard; with sealed + switch it is the reverse: a new operation is easy, and when a new type is added, every switch gives a compile error. This is the "expression problem".
📖 Answer
Since Java 21:
public sealed interface Shape permits Circle, Rect, Triangle {}
public record Circle(double r) implements Shape {}
public record Rect(double w, double h) implements Shape {}
public record Triangle(double b, double h) implements Shape {}
static double area(Shape s) {
return switch (s) {
case Circle c -> Math.PI * c.r() * c.r();
case Rect r -> r.w() * r.h();
case Triangle t -> t.b() * t.h() / 2;
}; // no default needed: the compiler checks exhaustiveness
}
A comparison:
| Abstract method (OOP) | Sealed + switch | |
|---|---|---|
| Adding a new type | one new class | every switch changes (the compiler shows you) |
| A new operation | every class changes | one new method |
| Type hierarchy | open | closed, known |
When I choose sealed:
- the set of types is stable and defined by the domain: a payment result (
Success,Declined,Error), AST nodes, event types; - the operations live in different layers (conversion to JSON, UI, calculation), and stuffing them into the domain class would violate SRP.
When I choose classic polymorphism:
- types are added from outside, like plugins (payment providers, export formats);
- the behavior is an intrinsic part of the type.
A trap: if you write default -> in a sealed hierarchy, you give up the exhaustiveness check, and when a new type is added the compiler stays silent.
Sign up to mark studied questions and save your progress.