Sub topic 18
Sealed Classes and Interfaces
In earlier chapters, any class could extend your abstract class or implement your interface. Usually that is what you want. Sometimes, though, you know the full list of types ahead of time. A traffic light has three colors. A payment is cash, card, or bank transfer. This chapter shows how to tell Java "these types, and no others."
What a Sealed Type Is
A sealed type is a class or interface that lists exactly which classes may extend or implement it. Any class that is not on the list gets a compile error if it tries to extend or implement the sealed type.
Sealed types became a standard Java feature in Java 17. You need Java 17 or newer to run the examples below, and the last example needs Java 21.
Here are the new words you will see:
sealedis a modifier that marks a class or interface as closed to outsiders.permitsis a clause that names the allowed subtypes.- A permitted subclass is one of the classes named in the
permitsclause.
Why Close a Hierarchy?
A hierarchy is a family of types connected by extends and implements. An open hierarchy can grow forever. Anyone can add a new subclass, even in code you never see.
A closed hierarchy has some useful properties:
- You know every case. When you check what kind of object you have, you can be sure you covered them all.
- Your design stays fixed. No one can add a strange subclass that breaks your assumptions.
- The compiler can help you. In newer Java versions, the compiler checks that your code handles every permitted type.
A First Example
This program uses a sealed interface called Vehicle. Only Car and Truck may implement it.
sealed interface Vehicle permits Car, Truck {}
final class Car implements Vehicle {}
final class Truck implements Vehicle {}
public class Main {
static String describe(Vehicle v) {
if (v instanceof Car) {
return "car";
} else if (v instanceof Truck) {
return "truck";
}
throw new IllegalStateException();
}
public static void main(String[] args) {
System.out.println(describe(new Car())); // prints: car
}
}Save this as Main.java, then run java Main.java. It prints car.
Look at each part:
sealed interface Vehiclemarks the interface as sealed.permits Car, Truckgives the full list of allowed implementers.final class Carsays no class may extendCar.- The
describemethod checks for each type withinstanceof. Theinstanceofoperator tests whether an object belongs to a given type.
Suppose you add this line:
final class Bike implements Vehicle {}The compiler rejects it, because Bike is not in the permits list.
The Three Choices for a Permitted Subclass
Every permitted subclass must say what happens below it. It must use exactly one of these three modifiers:
| Modifier | Meaning | Who can extend it? |
|---|---|---|
| `final` | The hierarchy stops here. | No one. |
| `sealed` | It is closed too, with its own `permits` list. | Only the classes it lists. |
| `non-sealed` | It is open again. | Any class. |
If you leave the modifier off, the code does not compile. Java makes you choose on purpose.
Sealed Abstract Classes
Sealing works on abstract classes too. The next example uses all three modifiers.
sealed abstract class Shape permits Circle, Square, Polygon {
public abstract double area();
}
final class Circle extends Shape {
private final double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
sealed class Square extends Shape permits ColoredSquare {
protected final double side;
Square(double side) {
this.side = side;
}
@Override
public double area() {
return side * side;
}
}
final class ColoredSquare extends Square {
private final String color;
ColoredSquare(double side, String color) {
super(side);
this.color = color;
}
public String color() {
return color;
}
}
non-sealed class Polygon extends Shape {
@Override
public double area() {
return 0.0;
}
}
class Triangle extends Polygon {
@Override
public double area() {
return 6.0;
}
}
public class Main {
public static void main(String[] args) {
Shape[] shapes = {
new Circle(1.0),
new ColoredSquare(2.0, "red"),
new Triangle()
};
for (Shape s : shapes) {
System.out.println(s.getClass().getSimpleName() + ": " + s.area());
}
}
}The output is:
Circle: 3.141592653589793
ColoredSquare: 4.0
Triangle: 6.0Triangle is allowed even though Shape never names it. Polygon is non-sealed, so anyone may extend Polygon. The tree is closed at the top and open again on one branch.
Rules That Trip Up Beginners
Keep these rules in mind:
- Location. Permitted subclasses must sit in the same package as the sealed type. If your project uses Java modules, they must be in the same module instead.
- Same file shortcut. If all the permitted subclasses are in the same source file as the sealed type, you may leave out the
permitsclause. Java then works out the list from that file. Writing the list anyway makes your intent clearer. - Records and enums. A record is a short way to write a class that just holds data. Records are automatically
final, so they work well as permitted subtypes and need no extra modifier.
Exhaustive Checks with switch (Java 21)
In the first example, describe needed a throw at the end. The compiler could not be sure that v was a Car or a Truck. Java 21 adds pattern matching for switch, which lets a switch test an object's type. With a sealed type, the compiler knows the full list of cases. It accepts a switch with no default branch only if every permitted type is covered.
sealed interface Payment permits Cash, Card, Transfer {}
record Cash(double amount) implements Payment {}
record Card(double amount, String number) implements Payment {}
record Transfer(double amount, String iban) implements Payment {}
public class Main {
static String describe(Payment p) {
return switch (p) {
case Cash c -> "Cash: " + c.amount();
case Card c -> "Card ending " + c.number().substring(c.number().length() - 4);
case Transfer t -> "Transfer to " + t.iban();
};
}
public static void main(String[] args) {
System.out.println(describe(new Cash(10.0)));
System.out.println(describe(new Card(25.0, "1234567812345678")));
System.out.println(describe(new Transfer(99.0, "DE001234")));
}
}The output is:
Cash: 10.0
Card ending 5678
Transfer to DE001234Now add a fourth type, Crypto, to the permits list. The switch stops compiling until you add a case Crypto. The compiler finds every place you forgot to update, so you don't have to hunt for them.
When to Use Sealed Types
Use a sealed type when:
- The set of cases is fixed and part of your design, like payment methods or the states of an order.
- You want the compiler to check that every case is handled.
Avoid sealing when other programmers are supposed to add their own implementations. A plugin interface, for example, should stay open.
Exercise
A class declares sealed class Animal permits Dog, Cat {}. You then write class Dog extends Animal {}. Why does this fail to compile, and what are the three ways to fix the declaration of Dog?
Show answer
Every permitted subclass must declare whether the hierarchy continues below it, and Dog has no modifier. Fix it by writing final class Dog extends Animal {} (no subclasses), sealed class Dog extends Animal permits ... (only listed subclasses), or non-sealed class Dog extends Animal {} (any class may extend Dog).
Exercise
In the Shape example, can you write class Hexagon extends Shape {}? Can you write class Hexagon extends Polygon {}? Explain both answers.
Show answer
class Hexagon extends Shape {} fails because Hexagon is not in Shape's permits list. class Hexagon extends Polygon {} compiles, because Polygon is non-sealed and any class may extend it.
Exercise
In the Java 21 Payment example, you add record Crypto(double amount) implements Payment {} and add Crypto to the permits list. What happens to the describe method, and why is this useful?
Show answer
The switch no longer compiles, because it is not exhaustive: it has no case for Crypto. This is useful because the compiler points to every switch you need to update, so no new payment type goes unhandled.