Sub topic 16
Closed Hierarchies with Sealed Types and switch Patterns
In earlier chapters, each class supplied its own behavior by overriding a method. A Circle knew its own area, and a Square knew its own. This chapter shows a second way to organize the same idea. You list every kind of shape up front. Then one method handles each kind in turn, and the compiler checks that you did not forget any.
The features in this chapter need Java 21 or later. Sealed types came in Java 17. Pattern matching for switch became a final feature in Java 21.
What "Sealed" Means
A hierarchy is a family of types: one parent type plus all the classes that extend or implement it. Normally a hierarchy is open. That means anyone can write a new class that extends your class or implements your interface.
A sealed type is a class or interface that names every type allowed to extend or implement it. No other type may join. The list of allowed types goes in a permits clause, which is a list of class names after the keyword permits.
sealed interface Shape permits Circle, Square {}This line says: "Shape is an interface. Only Circle and Square may implement it." If someone writes class Triangle implements Shape, the code will not compile.
Rules for the permitted types
Every permitted type must say how it continues the hierarchy. It must use exactly one of these three modifiers:
| Modifier | Meaning | When to use it |
|---|---|---|
| `final` | No class may extend this one. | The usual choice. The hierarchy stops here. |
| `sealed` | This class has its own `permits` list. | You want a smaller closed family underneath. |
| `non-sealed` | Any class may extend this one again. | You want one branch to stay open. |
The permitted types must also sit close to the sealed type. They must be in the same package, or in the same module if you use modules. If they are all in the same source file, you may leave out the permits clause, and Java works out the list for you.
A Complete Example
Here is a full program. Save it as Main.java. Run it with java Main.java, or compile with javac Main.java and then run java Main.
public class Main {
static double area(Shape s) {
return switch (s) {
case Circle c -> Math.PI * c.radius * c.radius;
case Square q -> q.side * q.side;
};
}
public static void main(String[] args) {
Shape[] shapes = { new Circle(1.0), new Square(2.0) };
for (Shape s : shapes) {
System.out.println(area(s));
}
}
}
sealed interface Shape permits Circle, Square {}
final class Circle implements Shape {
final double radius;
Circle(double radius) { this.radius = radius; }
}
final class Square implements Shape {
final double side;
Square(double side) { this.side = side; }
}The output is:
3.141592653589793
4.0Main comes first in the file on purpose. When you run a single file with java Main.java, Java looks for main in the first class of the file.
How the switch works
A switch expression is a switch that produces a value. Here, that value is returned. Each case Circle c is a type pattern. A type pattern checks the runtime type of s. If the object really is a Circle, the pattern creates a new variable c of type Circle, and the code after -> runs.
This is the same idea as instanceof pattern matching from the casting chapter. The switch version tests several types in one place.
Why No `default` Branch Is Needed
A switch expression must be exhaustive. That means it must handle every possible value. With an open interface, the compiler cannot know every class that might implement it, so you would need a default branch.
With a sealed interface, the compiler knows the full list: Circle and Square. Both are covered, so the switch is complete.
You get a bigger benefit when the hierarchy changes. Suppose you add a third shape:
sealed interface Shape permits Circle, Square, Triangle {}
final class Triangle implements Shape {
final double base;
final double height;
Triangle(double base, double height) {
this.base = base;
this.height = height;
}
}Now area no longer compiles. The compiler reports an error like this:
error: the switch expression does not cover all possible input valuesThe compiler points you to every switch that needs a new case. You add one line:
case Triangle t -> 0.5 * t.base * t.height;Sealed Switch or Overriding?
You have now seen two designs for the same task.
- Overriding. Each class has its own
area()method. A call likes.area()uses dynamic dispatch to run the right one. - Sealed switch. The classes hold only data. One
area(Shape)method uses a switch to choose the behavior.
Each design makes one kind of change easy and the other kind harder.
| Change you want to make | Overriding | Sealed switch |
|---|---|---|
| Add a new kind of shape | Easy. Write one new class. Nothing else changes. | Harder. Every switch must get a new case, but the compiler finds them for you. |
| Add a new operation, such as `perimeter` | Harder. You must edit every shape class. | Easy. Write one new method with one switch. |
| Let other people add their own shapes | Works. The hierarchy stays open. | Not allowed. The hierarchy is closed. |
A simple rule of thumb:
- Use overriding when new types will keep arriving, especially from code you do not control.
- Use a sealed type with switch when the set of types is fixed and small, and you expect to add many operations over it.
You can also mix them. A sealed interface can still declare an abstract method that each class overrides.
Records Make This Shorter
A record is a short way to write a class that only holds data. Java writes the constructor, the accessor methods, and equals, hashCode, and toString for you. Records are always final, so they fit sealed hierarchies well.
Java 21 also adds record patterns. A record pattern takes the record apart in the case line.
public class Main {
static double area(Shape s) {
return switch (s) {
case Circle(double r) -> Math.PI * r * r;
case Square(double side) -> side * side;
};
}
public static void main(String[] args) {
System.out.println(area(new Circle(1.0)));
System.out.println(area(new Square(3.0)));
System.out.println(new Square(3.0));
}
}
sealed interface Shape permits Circle, Square {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}The output is:
3.141592653589793
9.0
Square[side=3.0]case Circle(double r) checks that s is a Circle and puts its radius into a new variable r. The last line shows the toString that the record wrote for you.
Edge Cases to Know
nullinput. Ifsisnull, the switch throws aNullPointerException. To handlenullyourself, addcase null -> 0.0;as a branch.- Sealed classes, not only interfaces. You can seal a class too, for example
abstract sealed class Shape permits Circle, Square. The rules are the same. non-sealedbreaks exhaustiveness only partly. IfSquareisnon-sealed, other classes may extend it. Acase Square qstill covers all of them, because each one is aSquare. The switch stays exhaustive.- Case order matters. A broad pattern placed before a narrower one causes a compile error, because the narrower case could never run. Put more specific types first.
- Guards. You can add a condition with
when, for examplecase Circle c when c.radius == 0 -> 0.0;. A guarded case does not count toward exhaustiveness, so you still need an unguardedcase Circle cafter it.
Exercise
You have sealed interface Vehicle permits Car, Bike {} with final class Car and final class Bike. A method uses return switch (v) { case Car c -> 4; case Bike b -> 2; };. A teammate adds Truck to the permits list and writes final class Truck implements Vehicle. What happens when they compile, and what is the fix?
Show answer
The switch no longer compiles. The compiler reports that the switch expression does not cover all possible input values, because Truck has no case. The fix is to add a branch such as case Truck t -> 6;. Adding a default branch would also compile, but then the compiler would stop warning about future new types.
Exercise
Why must each class listed in a permits clause be marked final, sealed, or non-sealed?
Show answer
The sealed type promises a known, closed set of subtypes. Each permitted class has to say whether that promise continues below it. final means no more subclasses. sealed means a further fixed list. non-sealed deliberately opens that one branch again. Without one of these modifiers, the compiler could not tell how far the closed hierarchy reaches.
Exercise
Your program has five shape types that rarely change, and you often add new calculations such as area, perimeter, and drawing. Which design fits better, overriding or a sealed type with switch? Explain in one or two sentences.
Show answer
A sealed type with switch fits better. Each new calculation is one new method with one switch, and you do not need to edit all five classes. Because the set of types is fixed, the compiler's exhaustiveness check keeps every switch complete.