Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Modern Java

    Sealed Types and Pattern Matching

    A sealed class or interface (Java 17) lists exactly which classes may extend or implement it, using permits. Nobody else can.

    Chapter 10 of 115 min read

    The Plain Picture#

    A form with a closed list of options: "Payment method: ☐ UPI ☐ Card ☐ Net banking". No "other". Because the list is closed, a clerk processing the form can have a rule for each option and know nothing was missed.

    The Real Names#

    • A sealed class or interface (Java 17) lists exactly which classes may extend or implement it, using permits. Nobody else can.

    • Pattern matching for switch (Java 21) lets a switch test an object's type, bind it to a variable, add conditions with when (a guard), handle case null, and even take records apart (record patterns).

    • Together they give exhaustive switches: over a sealed type, the compiler checks every permitted subtype is handled — no default needed.

    Under the Hood#

    Java
    sealed interface Shape permits Circle, Rect, Tri {}
    
    record Circle(double r) implements Shape {}
    
    record Rect(double w, double h) implements Shape {}
    
    record Tri(double b, double h) implements Shape {}
    
    static double area(Shape s) {
        return switch (s) {
            case Circle c -> Math.PI * c.r() * c.r(); // type pattern: bind to c
            case Rect(double w, double h) -> w * h; // RECORD pattern: pull out the components directly
            case Tri t when t.b() == 0 -> 0; // guard with `when`
            case Tri t -> 0.5 * t.b() * t.h();
        }; // no default: the compiler knows these are ALL the Shapes
    }
    // area(Circle(1)) = 3.14, area(Rect(2,3)) = 6.0, area(Tri(4,5)) = 10.0, area(Tri(0,5)) = 0.0

    Remove the Rect and Tri cases and the compiler says:

    Output
    error: the switch expression does not cover all possible input values

    So when someone later adds a Square to the permits list, every switch that forgot it becomes a compile error — instead of a silent bug at run time. This is the modern alternative to the if (type.equals(...)) chains of Object-Oriented Programming Part 0, for cases where the set of types is fixed and you want the logic outside the classes (e.g. many different operations over the same small family of shapes, payment events, AST nodes).

    Switching on any object:

    Java
    static String describe(Object o) {
        return switch (o) {
            case null -> "null!"; // null handled explicitly — no NullPointerException
            case Integer i when i > 100 -> "big int " + i; // more specific guarded case first
            case Integer i -> "int " + i;
            case String s -> "string of length " + s.length();
            default -> "something else"; // Object isn't sealed, so default is required
        };
    }
    // big int 500 | int 5 | string of length 3 | null! | something else

    Sealed + records vs polymorphism (Object-Oriented Programming Ch 4): with polymorphism, each class carries its own behaviour, and adding a new type is easy. With sealed + pattern matching, the types are fixed, and adding a new operation is easy (write one more switch). Pick based on which is more likely to change. This choice is known as the expression problem.

    Check yourself

    4 questions
    1

    What does sealed ... permits do?

    Show answer

    Restricts which classes can extend/implement the type to exactly the listed ones.

    2

    Why does a switch over a sealed type need no default?

    Show answer

    The compiler knows every possible subtype, so it can check the cases are exhaustive.

    3

    What does case Rect(double w, double h) do?

    Show answer

    It matches a Rect and extracts its record components into variables w and h.

    4

    When would you choose sealed types + switch over polymorphic methods?

    Show answer

    When the set of types is fixed but you keep adding new operations over them (keep logic outside the classes); polymorphism suits frequently added types.