Sub topic 10
What Sealed Types Do Not Allow
This chapter assumes you can declare a sealed type with sealed and permits, and that you know final, sealed and non-sealed. It covers the rules that make the compiler reject code, and the cases where the JVM or the standard library refuses a sealed type at runtime. Knowing these rules helps you read the error messages and decide whether a sealed type fits your design.
Restrictions are what make the guarantee
A sealed type promises that the compiler and the JVM know every direct subtype. That promise only holds if some things are forbidden. Each restriction below protects one part of it:
- The list of subtypes is explicit or can be derived from one source file.
- Every subtype states how far the hierarchy continues below it.
- No subtype can appear from somewhere the author did not control.
Only listed types may extend the sealed type
If a class names a sealed type in its extends or implements clause, that class must be a permitted subclass. Suppose Shape is sealed and permits Circle and Square. A third class cannot join, even in the same package:
// Shape.java
public sealed interface Shape permits Circle, Square {}
// Circle.java
public record Circle(double radius) implements Shape {}
// Square.java
public record Square(double side) implements Shape {}
// Triangle.java -- does not compile: Triangle is not in Shape's permits clause
public record Triangle(double base, double height) implements Shape {}The only fix is to edit Shape and add Triangle to permits. That is the intended friction. Adding a variant is a deliberate change to the type that owns the list.
The check also runs in the other direction. A class in a permits clause must really extend or implement the sealed type. Listing a class that does not is a compile error.
Permitted subclasses must be direct subtypes
The permits clause names direct subclasses only. A grandchild never appears in it:
sealed class Animal permits Dog {}
sealed class Dog extends Animal permits Puppy {}
final class Puppy extends Dog {}
// Does not compile: Puppy extends Dog, not Animal directly
// sealed class Animal permits Dog, Puppy {}Puppy is controlled by Dog's own permits clause, so each level of the hierarchy decides for itself.
Every permitted subclass must choose a modifier
A permitted subclass must be exactly one of final, sealed or non-sealed. Leaving the modifier out is an error, and combining two of them is also an error:
sealed interface Vehicle permits Car, Boat, Plane {}
final class Car implements Vehicle {}
sealed class Boat implements Vehicle permits Ferry {}
final class Ferry extends Boat {}
non-sealed class Plane implements Vehicle {}
// Each of these does not compile:
// class Truck implements Vehicle {} // no modifier
// final sealed class Bus implements Vehicle {} // two modifiersTwo related errors catch people:
non-sealedis only legal on a class or interface that has a sealed direct supertype. Writing it on an ordinary class is an error.- A
sealedclass needs at least one permitted subclass. If you declaresealed class Lonely {}with nopermitsclause and no subclass in the same compilation unit, the compiler rejects it.
Records are implicitly final, so they need no modifier and cannot be declared sealed or non-sealed. An enum is implicitly final, or implicitly sealed if some constants have class bodies. You cannot write these modifiers on an enum.
Location rules: module or package
A sealed type and its permitted subclasses must be in the same module. If the code is not in a named module, they must be in the same package.
| Setup | Where permitted subclasses may live |
|---|---|
| Named module (has `module-info.java`) | Any package in the same module |
| Unnamed module (classpath) | Same package only |
| Same source file | Always allowed, and `permits` may be omitted |
In a named module, the sealed type can be in one package and its subclasses in another:
// module-info.java
module shapes.core {
exports shapes.api;
}// shapes/api/Shape.java
package shapes.api;
public sealed interface Shape permits shapes.impl.Circle {}// shapes/impl/Circle.java
package shapes.impl;
import shapes.api.Shape;
public record Circle(double radius) implements Shape {}Without module-info.java, this layout fails because Circle is in a different package from Shape. Two sealed-type authors in separate jars on the classpath also cannot cooperate. Even if both jars use the same package name, the compiler cannot treat them as one module.
Each permitted subclass must also be accessible to the sealed class. A package-private subclass in another package, for example, cannot be named in permits.
No anonymous classes, local classes or lambdas
Anonymous and local classes cannot extend a sealed type, because they could never be listed in permits:
sealed interface Task permits Job {}
final class Job implements Task {}
class Demo {
void run() {
// Does not compile: anonymous classes cannot extend a sealed type
// Task t = new Task() {};
// Does not compile: local classes cannot extend a sealed type
// class Local implements Task {}
}
}Lambdas follow the same rule. A sealed interface cannot be the target type of a lambda or method reference, even if it has exactly one abstract method:
sealed interface Handler permits LoggingHandler {
void handle(String message);
}
final class LoggingHandler implements Handler {
public void handle(String message) {
System.out.println(message);
}
}
// Does not compile: a sealed interface is not a functional interface target
// Handler h = message -> System.out.println(message);If you want lambdas, the interface must not be sealed. A sealed type and a lambda-friendly type are different design choices.
The compiler is not the only enforcer
The JVM records the permitted subclasses in the class file. When a class loads, the JVM checks that its superclass or superinterface permits it. If you compile Triangle against an old copy of Shape that did not seal anything, and then run it against the new sealed Shape, loading fails with IncompatibleClassChangeError. This closes the loophole of bypassing javac with a hand-crafted class file.
The standard library enforces it too. java.lang.reflect.Proxy refuses sealed interfaces, because the generated proxy class would be an unlisted implementation. This means mocking frameworks that rely on dynamic proxies or subclass generation can fail on sealed types. Check how your test tools handle them before you seal a type that tests need to stub.
What sealed does not restrict
Some limits are not part of sealing:
- Sealing does not limit who can use or call the type. Access modifiers (
public, package-private) still control that. - Sealing does not limit instances. You can create as many instances of a permitted class as you like. For a fixed set of instances, use an enum.
- A
non-sealedsubclass reopens the hierarchy below it. The compiler then cannot assume it knows all subtypes below that point. finalon a subclass limits only that branch.
The last point matters for exhaustive switches:
sealed interface Node permits Leaf, Branch {}
final class Leaf implements Node {}
non-sealed class Branch implements Node {}
class SpecialBranch extends Branch {} // legal: Branch is non-sealed
static String kind(Node n) {
return switch (n) {
case Leaf l -> "leaf";
case Branch b -> "branch"; // also covers SpecialBranch
};
}The switch is still exhaustive, because Branch itself is a case and its subclasses are also Branch values. A non-sealed branch does not weaken exhaustiveness. It only means you cannot enumerate the subtypes under Branch.
A decision path for compile errors
When the compiler rejects a subclass of a sealed type, check these questions in order:
Common mistakes
- Putting subclasses in another package on the classpath. The error looks like a missing
permitsentry, but the real cause is the package rule. Either move the files or add amodule-info.java. - Listing indirect descendants in
permits. List only direct children. - Forgetting the modifier on a nested subclass. A
recordis fine, but a plain nestedclassneedsfinal,sealedornon-sealed. - Sealing an interface and then trying to pass a lambda. Use an abstract class or a record implementation instead, or leave the interface open.
- Sealing a type that a mocking library needs to subclass. Test with real instances, or keep the type open.
Exercises
Exercise
A sealed interface Event is in package app.events and is used on the classpath, with no module-info.java. A teammate adds final class Click implements Event {} in package app.ui and lists it in Event's permits clause. The compiler rejects it. Give the cause and two ways to fix it.
Show answer
Without a named module, permitted subclasses must be in the same package as the sealed type. Click is in app.ui, so the rule fails. Fix 1: move Click into app.events. Fix 2: add a module-info.java so that both packages belong to one named module, which allows permitted subclasses in different packages.
Exercise
Which of these declarations compile, assuming sealed interface S permits A, B, C, D {} and each name is a direct implementer? (1) record A() implements S {} (2) class B implements S {} (3) non-sealed class C implements S {} (4) final sealed class D implements S {}
Show answer
Only (1) and (3) compile. A record is implicitly final, so it needs no modifier. B has no final, sealed or non-sealed modifier. D combines final and sealed, and a subclass must choose exactly one.
Exercise
Why can a lambda not be used to create an instance of a sealed functional-shaped interface, and what is the practical alternative?
Show answer
A lambda produces an anonymous implementation that is not listed in the permits clause, so it would break the closed set of subtypes. Instead, write a permitted class or record that implements the interface and pass an instance of it. Or, if lambdas matter more than a closed hierarchy, do not seal the interface.