Modern Java Evolution

Sealed Types

A sealed class or interface names its complete set of direct subtypes with permits. The hierarchy becomes a closed algebraic data type: the compiler knows every case, and exhaustive switches need no default.
  • sealed interface X permits A, B, C — only A, B, C may implement X
  • Every permitted subtype must be final, sealed (continuing the closure), or non-sealed (reopening)
  • Same-file subtypes can omit permits; otherwise same module/package
  • Pairs with Records for data variants and pattern switches for processing
  • Use when the set of variants is a domain fact, not an extension point
A closed domain model
public sealed interface PaymentMethod
        permits Card, BankTransfer, Wallet {}

public record Card(String pan, YearMonth expiry) implements PaymentMethod {}
public record BankTransfer(String iban) implements PaymentMethod {}
public record Wallet(String provider, String accountId) implements PaymentMethod {}

Fee feeFor(PaymentMethod m) {
    return switch (m) {
        case Card c -> Fee.percent(1.5);
        case BankTransfer t -> Fee.flat(30);
        case Wallet w -> Fee.percent(2.0);
    };   // add GiftCard to permits → this switch fails to compile until handled
}

Sealing inverts the default openness of inheritance: instead of "anyone may extend" (Inheritance Polymorphism) or "no one may" (final), it says exactly these. That middle ground models real domains — a JSON value is null/bool/number/string/array/object, an AST has known node kinds, a payment is one of the supported methods. Libraries also seal to keep interface implementation rights internal while exposing the type.

Design guidance: seal when you enumerate the variants and adding one should force review of all processing code (the exhaustiveness compile errors are the feature). Keep interfaces unsealed when third parties are supposed to plug in (Interfaces). non-sealed deliberately punches a hole — rare, but it lets one branch reopen for extension (e.g., a sealed Shape with a non-sealed CustomShape escape hatch).

Sources
  • Core Java, Volume I: Fundamentals (13th ed.)Ch. 5.8 — Sealed Classes
  • Learning Java (6th ed.)Ch. 5 — Objects in Java