Sealed Classes: The Bouncer at the Door of Your Domain

Traditional Java interfaces are like public parks. Anyone, anywhere can implement them. This is powerful for creating public APIs and extensible plugins.

But sometimes… you don’t want an open party. You want an exclusive, VIP-only event. You want to model a domain where the specific variations are strictly known and controlled.

That is where Sealed Classes come in.

The Key Difference is Control

A sealed class (or interface) lets you, the author, act as the bouncer at the door. You explicitly declare, using the permits keyword, which specific classes are allowed to extend or implement it.

No one else is on the list.

public sealed interface PaymentMethod 
    permits CreditCard, PayPal, BankTransfer {
}

public final class CreditCard implements PaymentMethod { }
public final class PayPal implements PaymentMethod { }
public final class BankTransfer implements PaymentMethod { }

Why is this so powerful?

The true power of sealed classes is unlocked when you combine them with modern Java’s Switch Expressions and Pattern Matching.

When you use a switch on a sealed type, the compiler knows every single possible subtype.

public String processPayment(PaymentMethod method) {
    return switch (method) {
        case CreditCard c -> "Processing card";
        case PayPal p -> "Processing PayPal";
        case BankTransfer b -> "Processing transfer";
    }; // No default branch needed!
}

If you forget to handle one of the permitted types, it is a compile-time error.

This closes a huge loophole that traditional interfaces have, making your code significantly safer and more robust. You no longer have to throw IllegalArgumentException in a default case that you hope is never reached.

When to use which?

  • Use a standard interface when you want to define a public contract for anyone to implement (e.g., java.util.List).
  • Use a sealed class/interface when you want to model a domain that has a fixed, known set of variations (e.g., states in a state machine, specific types of events, or limited payment methods).

It is a powerful addition to our object-oriented design toolbox.