Sub topic 6
Sealed Interfaces: Closing a Type Hierarchy
This chapter assumes you know Java interfaces, classes and inheritance, and that you have used records and classic switch. You need JDK 17 or newer to compile sealed types. Pattern switch needs JDK 21.
Why close a hierarchy
An ordinary interface is open. Any class anywhere can implement it, so the compiler can never know the full list of implementations. That is why a switch over an open type always needs a default branch.
A sealed type states its direct subtypes in its declaration. The compiler and the reader then know the complete list. This is what lets a switch over the type omit default and still be checked for completeness. The next chapter covers that check. This chapter covers how to build a hierarchy that makes the check possible.
Declaring a sealed interface
Add the sealed modifier and list the allowed direct subtypes in a permits clause.
sealed interface Shape permits Circle, Rectangle, Square {}
record Circle(double radius) implements Shape {}
record Rectangle(double width, double height) implements Shape {}
record Square(double side) implements Shape {}Only Circle, Rectangle and Square may implement Shape directly. A class that writes implements Shape without being listed fails to compile.
Classes can be sealed as well:
abstract sealed class Account permits Checking, Savings {}
final class Checking extends Account {}
final class Savings extends Account {}The modifier each permitted subtype must choose
Every permitted direct subtype must say what happens to the hierarchy below it. It must use exactly one of these modifiers.
| Modifier | Meaning | Effect on the hierarchy |
|---|---|---|
| `final` | No further subtypes | The branch ends here |
| `sealed` | Further subtypes, but a listed set | The branch stays closed |
| `non-sealed` | Anyone may extend it | The branch becomes open again |
Records are implicitly final, so they need no modifier. Enums are implicitly final too, or implicitly sealed if some constants have bodies. This is why records and enums fit sealed hierarchies so well.
Mixing the three modifiers
A hierarchy can close some branches and reopen others:
sealed interface Shape permits Circle, Polygon, CustomShape {}
record Circle(double radius) implements Shape {}
sealed interface Polygon extends Shape permits Rectangle, Square {}
record Rectangle(double width, double height) implements Polygon {}
record Square(double side) implements Polygon {}
non-sealed interface CustomShape extends Shape {}The diagram shows the structure. The CustomShape branch is the only one whose implementations are unbounded.
Leaving out permits
If every permitted subtype is declared in the same source file as the sealed type, you may omit permits. The compiler infers the list from that file.
sealed interface Result {}
record Success(String value) implements Result {}
record Failure(String message) implements Result {}Here Result permits exactly Success and Failure. Omitting permits is convenient for small hierarchies. Write it explicitly when the subtypes live in separate files, because then it is required. An explicit list also makes the hierarchy easier to see at a glance.
Placement rules
The compiler enforces where permitted subtypes may live:
- In a named module, the sealed type and all its permitted subtypes must be in the same module. They may be in different packages.
- In the unnamed module (a classpath project with no
module-info.java), they must be in the same package. - Each permitted subtype must directly extend or implement the sealed type. Listing a grandchild in
permitsis an error. - Each permitted subtype must use
final,sealedornon-sealed, unless it is a record or an enum.
These rules keep the list of subtypes under the control of one team. Nobody outside the module can add a case.
Inspecting a sealed type at runtime
The Class API exposes sealing, which helps when you want to check what the compiler inferred. This program is complete and runnable:
import java.util.Arrays;
public class SealedDemo {
sealed interface Shape permits Circle, Square {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
public static void main(String[] args) {
System.out.println(Shape.class.isSealed());
Arrays.stream(Shape.class.getPermittedSubclasses())
.map(Class::getSimpleName)
.forEach(System.out::println);
}
}It prints true, then Circle, then Square.
What sealing buys you in a switch
A switch over a sealed type that covers every permitted subtype needs no default:
static double area(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Rectangle r -> r.width() * r.height();
case Square s -> s.side() * s.side();
};
}The benefit appears when the hierarchy changes. Suppose you add record Triangle(double base, double height) implements Shape {} and add it to permits. The area method now fails to compile with a message like "the switch expression does not cover all possible input values". The compiler has pointed you to every switch that needs a new case.
With a default branch, the same change would compile silently. The new type would fall into default, and you would find the bug at runtime or never. For this reason, avoid default when switching over a sealed type you control. A default throws away the check you sealed the type to get.
Common errors
These mistakes come up often.
- Forgetting a modifier. A permitted class that is not a record or enum must be
final,sealedornon-sealed. The compiler reports that the class must be declared one of these. - Listing a type that does not extend the sealed type. Each name in
permitsmust actually declareextendsorimplements. Otherwise the compiler reports an invalid permits clause. - Subtypes in the wrong place. Putting a permitted subtype in a different package of a classpath project fails, as does putting it in a different module.
- Anonymous classes and lambdas. You cannot create an anonymous subclass of a sealed type, because it would not be in the permitted list. A sealed interface also cannot be a functional interface target for a lambda.
- Expecting exhaustiveness through
non-sealed. Once a branch isnon-sealed, aswitchmust cover that branch type itself, for examplecase CustomShape cs. It cannot enumerate unknown implementations.
Choosing between sealed types, enums and open interfaces
The right tool depends on what varies between cases.
| Situation | Better choice |
|---|---|
| Fixed set of constants with the same fields | `enum` |
| Fixed set of cases, each carrying different data | Sealed interface with records |
| Unknown future implementations, plugins | Ordinary interface |
| Mostly fixed, with one deliberate extension point | Sealed with one `non-sealed` branch |
A sealed interface of records is the usual way to model "one of several shapes of data", such as parse results, commands and expression trees. You will build one in the final chapter of this tutorial.
Sealing does not prevent a type from having behavior. Sealed interfaces can declare methods, default methods and static helpers like any other interface. The choice between putting logic in methods and putting it in a switch is a design decision: methods suit cases that are open to growth, and a switch suits operations that are added more often than types.
Exercise
A sealed interface Vehicle permits Car, Truck and Bike, all written as ordinary classes with implements Vehicle and no modifiers. Why does this fail to compile, and what are the three valid fixes for each class?
Show answer
Each permitted subtype that is not a record or enum must be declared final, sealed or non-sealed. Without one of these the compiler cannot tell whether the hierarchy continues below that class. Use final to end the branch, sealed (with its own permits) to keep it closed with a known set of subtypes, or non-sealed to allow anyone to extend it. Converting a class to a record also works, because records are implicitly final.
Exercise
You have sealed interface Result {} with record Success(String value) and record Failure(String message) in the same file. A teammate writes static String show(Result r) { return switch (r) { case Success s -> s.value(); case Failure f -> f.message(); default -> "?"; }; }. What problem does the default create when someone later adds record Pending() implements Result {}?
Show answer
With default, the switch still compiles after Pending is added, so the compiler does not report the missing case. Every Pending value silently returns "?". Removing default makes the switch exhaustive over the sealed type, so adding Pending produces a compile error at this switch, and you add a case Pending p branch.