DEV Community

Benlyn Serrao
Benlyn Serrao

Posted on • Edited on

Java Sealed Classes

đź”’ What is a sealed class?
A sealed class is a special type of class in Java that restricts which other classes can extend or implement it.

Basically, You can control who subclasses it.

Let’s take a real-world example:

public sealed class PaymentMethod
    permits CreditCard, UPI, Wallet {}

public final class CreditCard extends PaymentMethod {}
public final class UPI extends PaymentMethod {}
public final class Wallet extends PaymentMethod {}
Enter fullscreen mode Exit fullscreen mode

Now, only these classes can extend PaymentMethod.

Let’s now look at how sealed classes help with type-safe switch expressions and pattern matching.

🎚️ Pattern Matching for Switch

The Java SE 21 release introduces pattern matching for switch expressions and statements (JEP 441) as a permanent feature. Pattern matching provides us more flexibility when defining conditions for switch selector expressions and cases.
You can read more about it here https://www.baeldung.com/java-switch-pattern-matching

We want to handle different PaymentMethods differently — and we want the compiler to force us to cover all the types (CreditCard, UPI, Wallet).

Classic instanceof + Cast (Before Java 17)

public void process(PaymentMethod payment) {
    if (payment instanceof CreditCard) {
        System.out.println("Processing credit card");
    } else if (payment instanceof UPI) {
        System.out.println("Processing UPI");
    } else if (payment instanceof Wallet) {
        System.out.println("Processing wallet");
    } else {
        throw new IllegalStateException("Unknown payment method");
    }
}

Enter fullscreen mode Exit fullscreen mode

what we can do now

public void process(PaymentMethod payment) {
    switch (payment) {
        case CreditCard c -> System.out.println("Processing credit card");
        case UPI u        -> System.out.println("Processing UPI");
        case Wallet w     -> System.out.println("Processing wallet");
    }
}


Enter fullscreen mode Exit fullscreen mode

Note: The compiler ensures all PaymentMethod subtypes are handled. If a new one is added later, this switch must be updated or it won’t compile.

đź’ˇ TL;DR

  • sealed lets you control subclassing

  • Great with pattern-matching switch in Java 17+

  • Compiler ensures exhaustive case handling

  • Code becomes safer and easier to maintain

Can you share how you've used sealed classes in combination with other Java features like pattern matching, records, or enums?

Top comments (0)