Sealed types
A sealed type names the subtypes it allows. The list is closed, so the compiler knows every implementation of an interface or every subclass of a class, and a switch over it can be checked for exhaustiveness. The keyword is sealed, the list is permits, and it is final in Java 17, so Java 21 has it in full.
sealed and permits
The interface declares itself sealed and names the two records that may implement it. Reflection shows the list the compiler recorded in the class file:
public class Permits {
public static void main(String[] args) {
for (Class<?> type : Shape.class.getPermittedSubclasses()) {
System.out.println(type.getSimpleName());
}
System.out.println(Shape.class.isSealed());
}
}
sealed interface Shape permits Circle, Square {
}
record Circle(double radius) implements Shape {
}
record Square(double side) implements Shape {
}
javac -Xlint:all Permits.java
java Permits
Circle
Square
true
getPermittedSubclasses is the run-time form of the clause, and it returns the two records in the order they are listed. A library that reads a hierarchy, a serialiser for example, can ask the same question and know that no third type exists.
Who may extend a sealed type
Every subtype must be listed, in the same package, and must itself be final, sealed or non-sealed. A record and an enum are final already, so they satisfy the rule without a keyword. A type that is not in the list is refused at its own declaration:
public class NotAllowed {
public static void main(String[] args) {
Shape shape = new Triangle(3);
System.out.println(shape);
}
}
sealed interface Shape permits Circle {
}
record Circle(double radius) implements Shape {
}
record Triangle(double side) implements Shape {
}
javac -Xlint:all NotAllowed.java
NotAllowed.java:14: error: class is not allowed to extend sealed class: Shape (as it is not listed in its 'permits' clause)
record Triangle(double side) implements Shape {
^
1 error
The message is the same for a class and for an interface, and it names the type that closed itself. The same file still holds the two declarations above it, which is why the error is at line 14 and not at the first line.
non-sealed
A permitted subtype may open the hierarchy again by declaring itself non-sealed. Then anyone may extend that subtype, and the compiler stops counting its descendants. The vehicle below is a sealed class with two permitted subclasses: one non-sealed, which a sports car extends, and one final:
public class Vehicles {
public static void main(String[] args) {
Vehicle[] vehicles = {new Car("car", 4), new SportsCar("sports", 2), new Bike("bike", 2)};
for (Vehicle vehicle : vehicles) {
System.out.println(vehicle.name() + " wheels " + vehicle.wheels()
+ " class " + vehicle.getClass().getSimpleName());
}
}
}
sealed abstract class Vehicle permits Car, Bike {
private final String name;
Vehicle(String name) {
this.name = name;
}
String name() {
return name;
}
abstract int wheels();
}
non-sealed class Car extends Vehicle {
private final int wheels;
Car(String name, int wheels) {
super(name);
this.wheels = wheels;
}
@Override
int wheels() {
return wheels;
}
}
final class SportsCar extends Car {
SportsCar(String name, int wheels) {
super(name, wheels);
}
}
final class Bike extends Vehicle {
private final int wheels;
Bike(String name, int wheels) {
super(name);
this.wheels = wheels;
}
@Override
int wheels() {
return wheels;
}
}
javac -Xlint:all Vehicles.java
java Vehicles
car wheels 4 class Car
sports wheels 2 class SportsCar
bike wheels 2 class Bike
getClass().getSimpleName() is the honest way to show which class answered: the call goes through Vehicle, and the third column says which override ran. A switch over Vehicle would now have to cover Car, which includes the unknown SportsCar, so the case is not exhaustive in the same sense; the class is sealed at the top and open below.
The permits clause you may omit
When every subtype is in the same source file, the compiler can see them all and permits may be left out. This is the form a small model uses, because all its pieces fit in one file:
public class Implicit {
public static void main(String[] args) {
for (Expr expr : new Expr[] {new Num(2), new Add(new Num(2), new Num(3))}) {
System.out.println(expr + " = " + eval(expr));
}
}
static int eval(Expr expr) {
return switch (expr) {
case Num(int value) -> value;
case Add(Expr left, Expr right) -> eval(left) + eval(right);
};
}
}
sealed interface Expr {
}
record Num(int value) implements Expr {
}
record Add(Expr left, Expr right) implements Expr {
}
javac -Xlint:all Implicit.java
java Implicit
Num[value=2] = 2
Add[left=Num[value=2], right=Num[value=3]] = 5
The recursion in eval works because a record pattern binds its components as Expr values, which the same switch then handles. A hierarchy in several files must write the clause, and a subtype in another module needs one more thing, a requires in the module descriptor.
Why a closed hierarchy matters
An open interface promises that anyone may add an implementation, so a switch over it needs a default and a default is a place where the next implementation is silently ignored. A sealed interface promises the opposite: the list is complete, so a switch without a default compiles and the compiler proves it covers every case. Add Mul(Expr left, Expr right) to the file above and eval stops compiling with a message that names the missing type; that is the design goal, a change that forces every reader of the hierarchy to decide.
The cost is that the hierarchy cannot be extended from outside, which is right for a model of a fixed set of things: an expression, a JSON value, a shape, a payment state. A plugin point stays an open interface. Lesson 061 writes the closed hierarchy that both features are made for.
Exercises
- Add Mul to Implicit.java and read the error the switch gives.
- Make Bike non-sealed and add an EBike below it.
- Move Triangle into the permitted list of NotAllowed and build it.
- Ask a sealed interface for its permitted subclasses after adding a third record, and print the count.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a sealed type declare?
Answer
The subtypes it permits, and no others
The permits list closes the hierarchy, and every subtype must be in it.
-
Which modifiers may a permitted subtype have?
Answer
final, sealed or non-sealed
The subtype either ends the chain, continues it, or opens it again.
-
When may the permits clause be omitted?
Answer
When every subtype is declared in the same source file
The compiler can see the whole file, so the list adds nothing it does not know.
-
What does this program print?
public class Q1 { public static void main(String[] args) { System.out.println(S.class.isSealed()); System.out.println(S.class.getPermittedSubclasses().length); } } sealed interface S permits A, B { } record A() implements S { } record B() implements S { }Answer
true then 2
The interface is sealed and both records are its permitted subclasses.
-
What does this program print?
public class Q2 { public static void main(String[] args) { System.out.println(area(new Square(3))); } static int area(S shape) { return switch (shape) { case Square(int side) -> side * side; case Circle(int r) -> 3 * r * r; }; } } sealed interface S permits Square, Circle { } record Square(int side) implements S { } record Circle(int r) implements S { }Answer
9
The switch covers the two permitted records and the square case wins.
-
What does this program print?
public class Q3 { public static void main(String[] args) { A a = new B(); System.out.println(a.getClass().getSimpleName()); } } sealed class A permits B { } final class B extends A { }Answer
B
The object is a B and getClass reports the runtime class.
-
What is the first line of the compiler output for this program?
public class Q4 { public static void main(String[] args) { System.out.println("x"); } } sealed interface S permits A { } record A() implements S { } record C() implements S { }Answer
error: class is not allowed to extend sealed class: S
The record C is not in the permits list, and the message names the sealed type.
-
What does this program print?
public class Q5 { public static void main(String[] args) { S s = new B(); System.out.println(s instanceof A); System.out.println(s.getClass() == A.class); } } sealed interface S permits A { } non-sealed class A implements S { } final class B extends A { }Answer
true then false
A non-sealed class may be extended, and B is an A but not exactly an A.
-
Why is a switch over a sealed interface better than one with a default?
Answer
A new subtype becomes a compile error instead of a silently ignored case
The closed list lets the compiler check every case, so a new subtype forces an update.
-
What does
non-sealedon a subtype do?Answer
Opens that subtype to extension by any class
The chain continues under that subtype, and the compiler stops tracking its descendants.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev