Script Valley
Java: Complete Language Course
Modern Java Features and Best PracticesLesson 6.4

Java sealed classes and pattern matching with switch

sealed class, permits clause, sealed interface, final subclasses, record patterns, switch pattern matching, exhaustiveness checking, algebraic data types

Sealed Classes and Pattern Matching

Sealed classes (Java 17) restrict which classes can extend a type. Combined with pattern matching switch, they enable exhaustive, compiler-verified type dispatch without fragile instanceof chains.

Sealed Hierarchy

public sealed interface Shape permits Circle, Rectangle, Triangle {}

public record Circle(double radius)           implements Shape {}
public record Rectangle(double w, double h)   implements Shape {}
public record Triangle(double base, double h) implements Shape {}

Pattern Matching Switch

public double area(Shape shape) {
    return switch (shape) {
        case Circle c       -> Math.PI * c.radius() * c.radius();
        case Rectangle r    -> r.w() * r.h();
        case Triangle t     -> 0.5 * t.base() * t.h();
        // No default needed โ€” compiler verifies all cases are covered
    };
}
System.out.println(area(new Circle(5)));         // 78.53...
System.out.println(area(new Rectangle(4, 6)));   // 24.0

Adding a new permitted subclass without updating every switch is a compile error, not a silent runtime bug. This exhaustiveness guarantee is the primary value of sealed classes over open hierarchies.

Subclasses must reside in the same package or module as the sealed type. Each must be declared final, sealed, or non-sealed. Records are implicitly final, making them natural permitted subclasses for data-focused hierarchies like AST nodes, event types, or result variants.

Up next

Java design patterns โ€” Builder, Strategy, and Observer

Sign in to track progress

Java sealed classes and pattern matching with switch โ€” Modern Java Features and Best Practices โ€” Java: Complete Language Course โ€” Script Valley โ€” Script Valley