Video in progress

Strong Junior 🧱 OOP and SOLID

What problem do sealed classes in Java 17 solve?

A sealed class or interface states exactly which classes may extend it, using permits. This closes the hierarchy: the compiler knows all the variants, and a switch is checked for completeness without a default.

📖 Answer

Ordinary inheritance is open: anyone, anywhere, can extend Payment. final forbids it entirely. Sealed is the middle option:

public sealed interface PaymentResult
        permits Success, Declined, Pending {}

public record Success(String txId) implements PaymentResult {}
public record Declined(String reason) implements PaymentResult {}
public record Pending(Duration retryAfter) implements PaymentResult {}

In Java 21, with a pattern matching switch:

String message = switch (result) {
    case Success s  -> "To'landi: " + s.txId();
    case Declined d -> "Rad etildi: " + d.reason();
    case Pending p  -> "Kuting: " + p.retryAfter().toSeconds() + " s";
};   // no default needed

If you add Refunded tomorrow, the compiler gives an error in every such switch, so none gets forgotten.

The rules:

  • every permitted child must be final, sealed or non-sealed (records are final automatically);
  • they must be in the same module, or in the same package if there are no modules.

Where you need it in practice: result types, states, commands, anywhere the set of variants is fixed by the domain. It does not fit places that are extended from outside, like plugins.