Sub topic 2
Declaring a Sealed Class or Interface
This chapter covers the declaration syntax: the sealed modifier, the permits clause, and what the compiler and the JVM check when they see them. It assumes you know Java inheritance and interfaces, the final keyword, access modifiers, packages, and the basics of records and switch expressions. The next chapters cover the subclass modifiers, the placement rules for permitted subclasses, and exhaustive switches in detail. They appear here only where the declaration needs them.
Sealed classes were previewed in Java 15 and 16 and finalized in Java 17. The examples below run on Java 17 or later.
The idea in one sentence
A sealed type names the classes that may directly extend or implement it. Any other class that tries gets a compile-time error.
Ordinary inheritance is open. Anyone with access to a non-final class can subclass it. final goes to the other extreme and allows no subclasses. Sealing sits between them: you allow a fixed list of subclasses and refuse the rest.
The basic syntax
Add the sealed modifier to a class or interface, then list the allowed direct subtypes after permits.
public class Main {
sealed interface Shape permits Circle, Square, Rectangle {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
record Rectangle(double width, double height) implements Shape {}
public static void main(String[] args) {
Shape s = new Circle(1.5);
System.out.println(s);
System.out.println(new Rectangle(2, 3));
}
}Save this as Main.java and run java Main.java. It prints Circle[radius=1.5] and Rectangle[width=2.0, height=3.0].
Three things are happening here:
Shapeis sealed, and itspermitsclause lists exactly three types.- Each listed type declares
implements Shape. Being listed is not enough. The subtype must also extend or implement the sealed type directly. - Records are implicitly
final, so they need no extra modifier. Other kinds of subclass must pick a modifier, which the next chapter covers.
What the header looks like
sealed and permits are contextual keywords. They only have special meaning in a type declaration header, so existing code that uses them as variable or method names still compiles.
The permits clause always comes last in the header, after extends and implements.
| Part | Required? | Notes |
|---|---|---|
| Access modifier (`public`, package-private) | Optional | Independent of sealing. A public sealed type can permit package-private subclasses. |
| `abstract` | Optional | Allowed on sealed classes. Sealed interfaces are already abstract. |
| `sealed` | Yes | Cannot be combined with `final` or `non-sealed` on the same type. |
| `class` or `interface` | Yes | Enums and records cannot be declared `sealed`. |
| `extends` / `implements` | Optional | Comes before `permits`. |
| `permits` | Usually | Can be omitted only when the subclasses are in the same compilation unit. See the chapter on permits rules. |
A header that uses most of these parts:
public sealed abstract class Vehicle extends Object implements Comparable<Vehicle>
permits Car, Truck {
// ...
}Sealed classes
A sealed class can be abstract or concrete, and it can have fields, constructors, and methods like any other class. If it is not abstract, you can still instantiate it directly.
public class Main {
public static void main(String[] args) {
Vehicle a = new Car("AB-123");
Vehicle b = new Truck("ZX-900", 12.5);
System.out.println(a.plate() + " / " + b.plate());
}
}
sealed abstract class Vehicle permits Car, Truck {
private final String plate;
protected Vehicle(String plate) {
this.plate = plate;
}
public String plate() {
return plate;
}
}
final class Car extends Vehicle {
Car(String plate) {
super(plate);
}
}
final class Truck extends Vehicle {
private final double loadTons;
Truck(String plate, double loadTons) {
super(plate);
this.loadTons = loadTons;
}
double loadTons() {
return loadTons;
}
}Run it with java Main.java. It prints AB-123 / ZX-900. The Vehicle constructor is protected, so only the permitted subclasses can call it in practice. Sealing adds a second layer on top of access control: even a subclass in the same package is refused unless it is listed.
Interface or abstract class?
Choose a sealed interface by default when the variants are mostly data. Records cannot extend a class, but they can implement an interface, so a sealed interface lets you use records for every variant. Choose a sealed abstract class when the variants share state or constructor logic, as Vehicle does with plate.
What the compiler checks
When it compiles a sealed type, javac enforces these rules.
- Every type named in
permitsmust directly extend or implement the sealed type. Listing a grandchild is an error. - Every direct subtype must be named in
permits, either explicitly or by inference from the same file. - Each permitted subtype must declare exactly one of
final,sealed, ornon-sealed. Records are implicitly final, and enums are implicitly final or sealed. - Each permitted subtype must be accessible to the sealed type, and the two must share a module or, in an unnamed module, a package. The details are in the chapter on permits rules.
- A sealed type must have at least one permitted subtype.
Here is rule 2 breaking:
sealed interface Shape permits Circle, Square {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
record Triangle(double base, double height) implements Shape {} // errorjavac reports an error saying that Triangle is not allowed to extend the sealed type Shape because it is not listed in its permits clause. The fix is a deliberate edit to Shape. You add Triangle to permits and then deal with every place that handles shapes.
The JVM enforces it too
Sealing is not only a compiler feature. The compiler writes the permitted list into the class file as a PermittedSubclasses attribute. When the JVM loads a class, it checks that attribute and refuses to load a subclass that is not listed.
This matters when you compile in separate steps. Suppose a library ships a sealed Shape, and you compile a Triangle against an older copy of the library that was not sealed. At run time the JVM then throws IncompatibleClassChangeError when it tries to load Triangle. The hierarchy is closed at run time as well as at compile time, so reflection and bytecode tricks cannot add a subclass.
Common mistakes
- Forgetting the
implementsorextendson a permitted type. Naming a type inpermitswithout it extending the sealed type is a compile error. - Naming an indirect subtype in
permits. IfB extends AandC extends B, thenAcan permit onlyB.Bcontrols what happens below it. - Leaving a permitted subtype without a modifier. A plain
class Car extends Vehicle {}fails, because it must befinal,sealed, ornon-sealed. - Trying to seal a record or enum. Neither can carry the
sealedmodifier. - Expecting a lambda to implement a sealed interface. Lambdas and anonymous classes cannot implement or extend a sealed type, because they cannot appear in the
permitslist. - Sealing a type with nothing in
permitsand no subclasses in the file. The compiler rejects a sealed type with no permitted subclasses.
Why declare it this way
The permits list is a contract that tools can read. Three things follow from it.
- Readers can see every variant in one place, without searching the codebase for subclasses.
- The compiler can reason about the full set of subtypes. Chapter six uses this for exhaustive
switchstatements that need nodefaultbranch. - Reflection can report the list at run time through
Class.isSealed()andClass.getPermittedSubclasses(), which a later chapter covers.
Exercise
A sealed interface Notification permits Email and Sms. A developer adds a class Push that implements Notification in another file in the same package, but forgets to edit the permits clause. What happens, and what is the minimal change that fixes it?
Show answer
The compiler rejects Push because it is not listed in the permits clause of Notification. The minimal fix is to add Push to the permits clause (permits Email, Sms, Push) and give Push one of the modifiers final, sealed or non-sealed. Any switch over Notification must then also handle Push.
Exercise
Why can you not declare a record as sealed, and what does a record do instead when it implements a sealed interface?
Show answer
A record is implicitly final, so it can have no subclasses and there is nothing for it to permit. When it implements a sealed interface it satisfies the "final, sealed or non-sealed" rule automatically through that implicit final modifier.