What are sealed classes/interfaces (Java 17), and when would you use them?

8 minadvancedsealed-classesjava17pattern-matching

Quick Answer

A sealed class or interface restricts which other classes/interfaces may extend or implement it, via an explicit permits clause. This lets you model a closed, known set of subtypes (like an algebraic data type) while still using inheritance, and lets the compiler exhaustively check switch expressions over that hierarchy.

Detailed Answer

Normally, any class can be subclassed (unless final) by anyone, anywhere. Sealed classes/interfaces (standardized in Java 17) let a type declare exactly which classes are allowed to extend/implement it, via permits:

sealed interface Shape permits Circle, Square, Rectangle { }

final class Circle implements Shape { double radius; }
final class Square implements Shape { double side; }
non-sealed class Rectangle implements Shape { double w, h; } // opens this branch back up

Each permitted subtype must itself be declared final (no further subtyping), sealed (continues restricting), or non-sealed (reopens unrestricted extension) — this forces every branch of the hierarchy to make an explicit choice.

Why use it: it models a closed, known set of variants — similar to algebraic data types / enums-with-data in other languages — while keeping normal class-based polymorphism. Combined with pattern matching for switch (finalized in Java 21, preview earlier), the compiler can verify a switch over a sealed type covers every permitted subtype, catching missing cases at compile time instead of via a runtime default:

double area(Shape s) {
    return switch (s) {
        case Circle c -> Math.PI * c.radius * c.radius;
        case Square sq -> sq.side * sq.side;
        case Rectangle r -> r.w * r.h;
        // no `default` needed — compiler proves exhaustiveness
    };
}

This is especially useful for domain models where you deliberately want to prevent uncontrolled extension (e.g., a fixed set of event types, request results, or expression-tree nodes).

Related Resources