Understanding Sealed Classes in Java


🔒 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 {}
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");
}
}
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");
}
}
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?
Subscribe to my newsletter
Read articles from Benlyn Serrao directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
