Video in progress

Middle ☕ Core Java

Why do you need sealed classes and interfaces?

sealed (Java 17) limits who can extend a class or implement an interface, with an explicit list. That gives you a closed hierarchy, and the compiler itself checks that a switch covers every case.

📖 Answer

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 {}

Now:

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

If Refunded is added tomorrow, every switch like this gives a compile error, so no place gets forgotten.

The rules:

  • a permitted subclass has to be final, sealed or non-sealed;
  • they have to be in the same module (or the same package, if there's no module).

When it's useful: result types (success/failure), domain states, commands, AST nodes: places where the number of variants is limited and known. It's like an extension of a plain enum, where each variant has its own fields.