Sub topic 12
Adding a permitted subclass and what breaks
Sealed hierarchies are closed when you write them, but they rarely stay that way. A new payment method, a new AST node or a new error kind means another permitted subclass. This chapter covers what happens to code that uses the hierarchy when you add one, and how to make that change safe.
It assumes you can write sealed hierarchies with permits, use pattern-matching switch over them without a default branch (Java 21 or later), and compile and run Java from the command line.
Why this change is special
With an open hierarchy, adding a subclass is invisible to existing code. Nobody wrote a switch that claims to know every subtype.
A sealed hierarchy is different because exhaustive switches depend on the list being complete. Adding a permitted subclass changes the meaning of every switch that relied on the old list. The effect depends on three things:
- Whether the client code is recompiled.
- Whether its
switchhas adefaultbranch. - Whether the new subclass is a direct permitted subclass or sits under a sealed intermediate type.
Starting point
This chapter uses a small hierarchy with one client method:
public sealed interface Shape permits Circle, Square {}public record Circle(double radius) implements Shape {}public record Square(double side) implements Shape {}public class Areas {
public static double area(Shape s) {
return switch (s) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Square q -> q.side() * q.side();
};
}
}Each public type goes in its own file. All four files are in the unnamed package. Areas has no default branch because the compiler knows Circle and Square cover every Shape.
What you must change to add a subclass
A new subclass is not accepted just because it says implements Shape. The sealed type has to agree to it. Two things must be true:
- The sealed type permits the new class. Either you add it to the
permitsclause, or it is declared in the same compilation unit whenpermitsis omitted. - The new class declares
final,sealedornon-sealed. Records and enums satisfy this implicitly.
Adding a new Triangle means editing Shape itself:
public sealed interface Shape permits Circle, Square, Triangle {}public record Triangle(double base, double height) implements Shape {}The author of the sealed type is the only person who can make this change. A class that implements Shape without being permitted gets a compile error, and the JVM rejects it at load time if someone bypasses the compiler.
Case 1: client recompiled, no default branch
Recompile Areas against the new Shape and the compiler stops you:
Areas.java:3: error: the switch expression does not cover all possible input valuesThis is the intended result. The compiler lists every place that needs a decision about the new variant. You fix each one by adding a case Triangle t -> ... branch.
This works only if you recompile. Build tools usually recompile dependents when a source file changes, but a library consumer using a prebuilt jar sees no error until they upgrade and rebuild.
Case 2: client has a default branch
Suppose the client was written like this:
public static String label(Shape s) {
return switch (s) {
case Circle c -> "round";
case Square q -> "boxy";
default -> "unknown";
};
}After you add Triangle, this code still compiles. Triangles silently get "unknown". A default branch makes the switch exhaustive on its own, so the compiler has nothing to check and the new variant produces no warning.
This is the main reason the guidance says to avoid default on sealed switches. A default turns a compile-time reminder into a quiet runtime behavior. Use one only when "anything else" is a deliberate rule, such as a fallback for unknown shapes in a plugin system.
Case 3: client not recompiled
Binary compatibility is a separate question from source compatibility. A class file compiled against the old Shape is still loaded against the new one when you swap in a new jar without rebuilding the client.
You can reproduce this with two source directories. src/v1 holds the four files above. src/v2 holds the new Shape.java and Triangle.java, plus this Main.java:
public class Main {
public static void main(String[] args) {
System.out.println(Areas.area(new Circle(1.0)));
System.out.println(Areas.area(new Triangle(3.0, 4.0)));
}
}Then compile and run:
mkdir -p out/v1 out/v2
javac -d out/v1 src/v1/*.java
javac -d out/v2 -cp out/v1 src/v2/*.java
java -cp out/v2:out/v1 MainThe old Areas.class comes from out/v1, and the new Shape and Triangle come from out/v2. The first line prints 3.141592653589793. The second call fails:
Exception in thread "main" java.lang.MatchException
at Areas.area(Areas.java:3)
at Main.main(Main.java:4)The compiler adds a hidden fallback branch to every exhaustive switch that has no default. If the value matches no case, that branch throws MatchException. In Java 21 and later this replaces older behavior. Switches over enums used to throw IncompatibleClassChangeError in that situation, and preview versions of pattern switches did the same. If you target an older runtime, expect the older error type.
The failure comes late. It appears only when a Triangle actually reaches the old switch, not at startup. Code paths that never see triangles keep working, so a test suite that never builds a triangle may not catch it.
Summary of outcomes
| Client situation | Compile time | Run time with a new `Triangle` |
|---|---|---|
| Recompiled, no `default` | Error until you add a case | Not reached |
| Recompiled, with `default` | No message | Triangle goes to `default` |
| Not recompiled, no `default` | Not applicable | `MatchException` |
| Not recompiled, with `default` | Not applicable | Triangle goes to `default` |
The diagram follows the same decisions as the table.
Adding under an intermediate sealed type
The impact depends on where in the hierarchy you add the class. Consider a hierarchy that has a sealed intermediate type:
sealed interface Shape permits Polygon, Circle {}
sealed interface Polygon extends Shape permits Square, Triangle {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape, Polygon {}
record Triangle(double base, double height) implements Polygon {}Clients can write switches at either level:
- A switch with
case Polygon pandcase Circle ccovers everyShape. AddingPentagonunderPolygonleaves it exhaustive, and it keeps compiling and running correctly. The new type falls into the existingPolygonbranch. - A switch with
case Square,case Triangleandcase Circlelists the leaves. AddingPentagonbreaks it exactly as in the earlier cases.
Clients that switch on the intermediate type are insulated from changes below it. Placing a sealed intermediate type where its subtypes share behavior gives you stable grouping points. It also gives clients a coarser, safer pattern to match on.
Other changes to the hierarchy
Adding a subclass is not the only edit that affects clients:
- Removing a permitted subclass. Code that names the removed type fails to compile. Old class files that reference it fail at run time with a missing-class error.
- Changing a modifier. Changing
finaltonon-sealedopens a branch to unlimited extension. A switch that listed it still compiles, since the type itself is unchanged. Changingnon-sealedtofinalbreaks outside code that extended it. - Removing
sealedentirely. Switches withoutdefaultstop compiling, because the compiler can no longer prove coverage. - Adding a case that is already covered. If a client's earlier branch (for example
case Polygon p) dominates a later one, the compiler reports that the later label is dominated. Order branches from specific to general.
Managing change as a library author
If the sealed type is part of a public API consumed by code you do not control, treat each new permitted subclass as a breaking change:
- Document the variant list as part of the contract, and bump the major version when it changes.
- Give clients a way to handle the unknown. Put a
non-sealedor an open subtype in the hierarchy only if you accept that clients then need adefaultbranch. - Keep the sealed type internal, and expose a smaller interface or an open type to outside code.
If every consumer is in your own codebase, you get the compile-time benefit. Build everything together, and let the compiler list every switch that needs updating.
A practical checklist for adding a variant inside one codebase:
- Add the subclass and update
permitsif it is explicit. - Do a full rebuild, not an incremental one.
- Fix every exhaustiveness error by adding the case.
- Search for switches with
defaultover this type, and decide for each whether the new type should reach it. - Add a test that builds an instance of the new type and passes it through the main code paths.
Exercise
A library publishes sealed interface Event permits Created, Deleted and you add Updated in the next release. An application uses the old compiled library classes plus its own already compiled switch (event) with cases for Created and Deleted and no default. After you upgrade only the library jar, what happens when an Updated event arrives, and how could the application have been written so that Updated fell back to a safe behavior?
Show answer
The old switch has no branch that matches Updated, so the compiler-generated fallback throws MatchException (Java 21 or later) at the moment the event reaches the switch. The application would have had to include a default branch, or the library would have had to avoid sealing the type. A default has the cost described above: after a recompile the application would no longer be told about new variants.
Exercise
Given sealed interface Node permits Leaf, Branch, sealed interface Branch extends Node permits Binary, Ternary and record Leaf(int v) implements Node {}, you add record Quad() implements Branch {}. Which of these client switches still compile after a rebuild: (a) cases Leaf, Branch; (b) cases Leaf, Binary, Ternary?
Show answer
Switch (a) still compiles and covers Quad through Branch. Switch (b) fails with a non-exhaustive error until you add a case for Quad, because it names the individual leaves of Branch.