Sub topic 1
Why You Might Want a Closed Hierarchy
Java classes and interfaces are open by default. Anyone who can see a non-final type can extend it, and that is often what you want. Sometimes it isn't. This chapter explains when you want the opposite, a type that lists every one of its direct subtypes. It also shows which problems that solves, how Java handled them before version 17, and what sealed types add. Later chapters cover the syntax and rules in detail.
Prerequisites
This chapter assumes you already know:
- Java classes, inheritance and interfaces, including abstract classes and
instanceof. - The
finalkeyword and the access modifierspublic,protected, package-private andprivate. - What a package is, and a rough idea of what a module is.
- Records and enums at a basic level.
- Switch expressions and basic generics.
To run the examples you need JDK 21 or later. The sealed keyword needs Java 17, and the exhaustive switch over types needs Java 21.
The problem: open hierarchies hide the complete list of cases
Suppose you model shapes and write a method that computes an area. With an ordinary interface, the code looks like this.
public class OpenDemo {
interface Shape {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
static double area(Shape shape) {
if (shape instanceof Circle c) {
return Math.PI * c.radius() * c.radius();
} else if (shape instanceof Square s) {
return s.side() * s.side();
} else {
throw new IllegalArgumentException("Unknown shape: " + shape);
}
}
public static void main(String[] args) {
System.out.println(area(new Square(3)));
}
}The final else branch is the interesting part. The compiler cannot know that Circle and Square are the only shapes, because any other class can implement Shape. So you must write a fallback, and that fallback can only fail at runtime.
Now a teammate adds this in another file:
record Triangle(double base, double height) implements Shape {}Everything still compiles. Every method like area now throws an exception when it receives a Triangle. Nothing points you to the places that need updating. You find them by testing, or in production.
The root problem is that the set of subtypes is part of your design, but the language has no way to record it. Only convention and documentation say "these are the only shapes".
What a closed hierarchy is
A closed hierarchy is a type whose complete list of direct subtypes is fixed in the source code and enforced by the compiler. Three parties use that list.
- The compiler rejects any class that tries to extend the type without being on the list.
- The people reading the code can see all the variants in one place.
- Tools and frameworks can ask for the list, at compile time or through reflection.
Closing a hierarchy is a design decision. You are saying that the type represents a fixed set of alternatives, such as "a payment is a card, a bank transfer or a voucher". You are not saying that it describes behavior any class might choose to provide.
How Java closed hierarchies before sealed types
Closed hierarchies existed before Java 17. They were just awkward, and each technique covered only part of the need.
| Technique | How it closes the hierarchy | Limitation |
|---|---|---|
| `final` class | No class can extend it | Closes it completely, so you get no variants at all |
| Package-private constructor | Only classes in the same package can call `super()` | Closed only against other packages. Any class in that package can still extend it, and the compiler cannot list the subtypes |
| Nested private classes | Subclasses are hidden implementation details | The subtypes are not part of the public API, so callers cannot name them or switch over them |
| `enum` | Fixed set of instances | Every case is one instance of the same class, with the same fields |
The package-private constructor approach looks like this.
public abstract class Shape {
Shape() {} // package-private: classes outside this package cannot extend Shape
public abstract double area();
}This keeps outsiders out, but it has two weaknesses. The compiler still sees an ordinary abstract class with no known subclass list, so it cannot check a switch for completeness. And the intent is invisible: a reader has to notice the missing public on the constructor.
Enums come closest. An enum is a closed set of values, and switch over an enum is checked for completeness. But every constant is an instance of one class with the same fields. A Circle with a radius and a Rectangle with a width and a height cannot both be enum constants. Sealed types fill that gap: a closed set of types, where each type has its own shape of data.
The same example, closed
Here is the shape model again, with the hierarchy sealed.
public class ClosedDemo {
sealed interface Shape permits Circle, Square {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
static double area(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Square s -> s.side() * s.side();
};
}
public static void main(String[] args) {
System.out.println(area(new Circle(1)));
System.out.println(area(new Square(3)));
}
}Three things changed.
sealedandpermitsstate the complete list of direct subtypes:CircleandSquare.- The
switchhas nodefaultand no fallback branch. The compiler checks that the cases cover every permitted subtype, so the code is complete as written. - If someone writes
record Triangle(...) implements Shape {}, the compiler rejects it, becauseTriangleis not in thepermitslist.
The more important change comes when you deliberately add Triangle to the permits list. Every switch like the one in area then stops compiling, and the compiler reports each place that lacks a Triangle case. A runtime failure becomes a compile-time error, and the compiler lists the code you need to update.
How the two designs compare
What a closed hierarchy buys you
- Compiler-checked completeness. A switch over the type must handle every variant, and adding a variant flags every switch that needs changing.
- Safe removal of fallbacks. You can drop the defensive
else throwbranches that exist only to satisfy the compiler. - A readable model. The
permitslist, or the nested declarations, documents the variants in one place. - Closer fit to the domain. Many domains really are closed. A parse result is a success or a failure. A JSON value is an object, array, string, number, boolean or null. An HTTP response in your client library is one of the outcomes you chose to handle.
- Library control. A library author can expose a type for callers to consume and switch over, while keeping the right to add behavior without letting callers create new implementations.
What you pay
A closed hierarchy gives up something an open one has: extensibility by other people. That cost is easy to underrate.
- Callers cannot add their own subtype. If your library's users need to plug in their own implementations, a sealed type is the wrong tool.
- Adding a variant is a breaking change for code that switches over the type. This is intended, but you must plan for it, particularly if the type is part of a public API. A later chapter covers it.
- Sealing a type that models behavior, such as a
Comparatoror aRunnable, makes little sense. Those types are open because the number of implementations is unbounded.
A useful test is to ask who will add the next subtype. If it will be you or your team, in the same codebase, a closed hierarchy fits. If it could be someone you've never met, keep it open.
Common misunderstandings
- "Sealed means final." A
finalclass has no subclasses. A sealed class has a known, limited set of them. - "Sealed is access control." It is not. A sealed type can be
publicand still allow only a few subtypes. Visibility controls who can see a type, andsealedcontrols who can extend it. - "Sealed types make switches exhaustive everywhere." Only a pattern
switchthat covers a sealed type is checked this way. A plainif/elsechain gets no check, and aswitchwith adefaultbranch is trivially complete. - "Enums already do this." They do, for a fixed set of instances. They don't do it when each case carries different data, which is where sealed types are used.
- "I can seal anything at runtime." Sealing is static. The
permitslist is recorded in the class file and enforced by the compiler and the JVM, and it cannot change while the program runs.
Summary of the idea
An open hierarchy answers the question "what can this type be?" with "anything". A closed hierarchy answers it with "exactly these". When the second answer matches your domain, you gain compiler help in the places where open hierarchies traditionally fail at runtime. The next chapters show how to declare sealed types and which modifiers their subtypes must use.
Exercise
A payment library defines interface PaymentMethod with implementations Card, BankTransfer and Voucher. The library's customers are other companies, and some of them write their own payment methods and pass them to the library. A colleague proposes making PaymentMethod sealed so that every switch over it is checked by the compiler. Is that a good idea? State the benefit, the cost, and your recommendation.
Show answer
The benefit is that every switch over PaymentMethod would be checked for completeness, so adding a variant would flag each switch that needs updating, and the fallback branches could be removed. The cost is that customers could no longer implement PaymentMethod themselves, because only the permitted subtypes could implement it. Since customers already write their own implementations, sealing would break that use and is not a good idea for this type. Keep PaymentMethod open. If the library needs a closed set internally, for example the built-in methods, it can use a separate sealed type for those, or leave the interface open and document that callers must handle unknown implementations.
Exercise
Look at this code and say what happens when a new class Pentagon implements Shape is added in another file, first with interface Shape {} and then with sealed interface Shape permits Circle, Square {}. Assume area is the switch-based method from the sealed example above.
Show answer
With the open interface Shape {}, Pentagon compiles, and area fails at runtime for a Pentagon (with an if/else chain it reaches the fallback throw). With the sealed interface, Pentagon implements Shape is a compile-time error because Pentagon is not in the permits list. If you then add Pentagon to permits, the switch in area stops compiling until you add a Pentagon case.