Your checkout accepts three ways to pay: card, UPI and wallet. That list is part of your business rules. Somewhere in the code, a method calculates fees for each one. Six months later someone adds CryptoPayment, and nothing tells them that the fee calculation, the refund logic and the receipt printer all need a new branch. The bug shows up in production.
Before Java 17, Java had no way to say “these are all the kinds of payment”. A class was either final (no subclasses at all) or open to anyone. Sealed classes fill the gap: you list the allowed subclasses, and the compiler holds everyone to it.
Sealed classes were previewed in Java 15 and 16 and became standard in Java 17 (JEP 409). Java 21’s pattern matching for switch is what makes them really shine.
What is a sealed class?
A sealed class or interface declares which classes are allowed to extend or implement it, using a permits clause:
// Java 17+
public sealed interface Payment permits CardPayment, UpiPayment, WalletPayment {}
public record CardPayment(String cardNumber, long amount) implements Payment {}
public record UpiPayment(String upiId, long amount) implements Payment {}
public record WalletPayment(String walletId, long amount) implements Payment {}
Now try to add a fourth:
public record CryptoPayment(String wallet, long amount) implements Payment {}
// error: class is not allowed to extend sealed class: Payment
// (as it is not listed in its 'permits' clause)
The set of payments is closed. To add one, you have to change the Payment declaration itself, which is exactly the place a reviewer will notice.
Why sealed classes are useful
They model “one of these” data honestly. A lot of domain data is a fixed set of alternatives: a payment is a card or UPI or wallet; a shape is a circle or a square; an API result is a success or a failure. Sealed types write that rule into the type system instead of a comment.
They make switch exhaustive. Because the compiler knows every subtype, a switch over a sealed type doesn’t need a default, and the compiler checks that every case is handled:
// Java 21
static long fee(Payment payment) {
return switch (payment) {
case CardPayment c -> c.amount() * 2 / 100; // 2%
case UpiPayment u -> 0;
case WalletPayment w -> w.amount() / 100; // 1%
};
}
Add CryptoPayment to the permits list and this method stops compiling with “the switch expression does not cover all possible input values”, along with every other switch over Payment. The compiler hands you the to-do list.
“With a sealed type, “did we handle every case?” stops being a code-review question and becomes a compiler error.”
They protect your design. In a library, a sealed type lets you hand out an interface without letting strangers implement it, so you can add methods or rely on the known implementations safely.
The rules
Every permitted subclass must choose: final, sealed or non-sealed
A subclass of a sealed class must say how it can be extended. There are three options:
| Modifier | Meaning |
|---|---|
final |
No further subclasses. The hierarchy stops here. (Records are implicitly final.) |
sealed |
Further subclasses allowed, but only the ones it lists in its own permits. |
non-sealed |
Open again: anyone may extend it. |
// Java 17+
public abstract sealed class Vehicle permits Car, Truck, Bike {}
public final class Car extends Vehicle {} // closed
public sealed class Truck extends Vehicle permits HeavyTruck {} // closed, one more level
public final class HeavyTruck extends Truck {}
public non-sealed class Bike extends Vehicle {} // open again
public class EBike extends Bike {} // allowed: Bike is non-sealed
Leave the modifier off and the compiler complains: “sealed, non-sealed or final modifiers expected”. The choice is forced so that nobody opens up a hierarchy by accident. non-sealed is the deliberate escape hatch, and it’s easy to spot in review.
Where permitted subclasses can live
- If your code is in a named module, the sealed class and its permitted subclasses must be in the same module.
- If it’s not in a module (the classpath, which is most applications), they must be in the same package.
- If all the subclasses are in the same source file as the sealed class, you can leave out
permitsand the compiler infers the list.
Records and sealed interfaces are made for each other
Records are implicitly final, so they satisfy the rule automatically, and a sealed interface can be implemented by records. That pairing (a sealed interface listing a handful of records) is the most common way you’ll see sealed types in modern Java. It’s often called an algebraic data type in other languages: a closed set of simple data shapes.
A practical example: a Result type
A method that can fail usually throws an exception or returns null. A sealed Result makes both outcomes explicit in the return type:
// Java 21
sealed interface Result<T> permits Success, Failure {}
record Success<T>(T value) implements Result<T> {}
record Failure<T>(String error) implements Result<T> {}
static Result<Integer> parse(String text) {
try {
return new Success<>(Integer.parseInt(text));
} catch (NumberFormatException e) {
return new Failure<>("not a number: " + text);
}
}
String message = switch (parse(input)) {
case Success<Integer>(Integer value) -> "got " + value;
case Failure<Integer>(String error) -> "error: " + error;
};
The caller can’t forget the failure case: the switch won’t compile without it. The Success(...) and Failure(...) parts are record patterns (Java 21), which take the record apart as they match. More on those in pattern matching for switch.
Checking sealed types with reflection
Frameworks can ask a class whether it’s sealed and which subclasses it permits:
Payment.class.isSealed(); // true
Payment.class.getPermittedSubclasses(); // [CardPayment, UpiPayment, WalletPayment]
Sealed vs final vs abstract vs enum
| Who can extend it? | Use it when | |
|---|---|---|
final class |
Nobody | One concrete type, no variations |
Regular / abstract class |
Anyone | You want an open extension point |
sealed class / interface |
Only the listed classes | A fixed set of kinds, each with its own data |
enum |
Nobody (fixed constants) | A fixed set of values with the same shape |
The enum comparison matters most. An enum is perfect when every option carries the same data (Status.ACTIVE, Status.CLOSED). When each option carries different data (a card number for one, a UPI ID for another), reach for a sealed interface with records.
Common mistakes
Adding default to a switch over a sealed type. It compiles, but it switches off the safety net: a new subtype silently falls into default instead of breaking the build. Leave default out when you’ve covered every permitted type.
Sealing things that should be open. If you genuinely want users of your code to add their own implementations (plugins, strategies), don’t seal it.
Forgetting the package rule. On the classpath, all permitted subclasses must share the sealed class’s package. Spreading them across packages gives a compile error.
Key takeaways
- A sealed class or interface lists its allowed subclasses with
permits; anything else is a compile error. - Standard since Java 17; Java 21’s pattern matching for switch makes them far more useful.
- Each permitted subclass must be
final,sealedornon-sealed. Records are implicitly final. - A
switchover a sealed type is checked for completeness, so adding a subtype shows you every place to update. - Sealed interfaces plus records model “one of these shapes of data”: payments, results, events, shapes.
Frequently asked questions
What is a sealed class in Java?
A class or interface that restricts which other classes may extend or implement it. You list the allowed subclasses in a permits clause, and the compiler rejects any other.
Which Java version introduced sealed classes?
Sealed classes were previewed in Java 15 and 16 and became a standard feature in Java 17 (JEP 409).
What is the difference between sealed and final in Java?
A final class can’t be extended at all. A sealed class can be extended, but only by the specific classes it permits.
What does non-sealed mean in Java?
non-sealed is a modifier for a permitted subclass that reopens the hierarchy: any class may extend it. It’s a deliberate, visible way out of the restriction.
Can a record implement a sealed interface?
Yes, and it’s the most common pattern. Records are implicitly final, so they meet the rules automatically.
Next in Modern Java: pattern matching for switch, where sealed types pay off.
Comments