Sealed classes and interfaces
A sealed class or interface lists exactly which classes may extend it. The compiler and the JVM then both know every possible subtype, which lets a switch be checked for completeness. This page explains how sealing is recorded and enforced, shows each modifier, the compiler's errors, sealed types compared with enums, and what happens when a sealed hierarchy changes after clients were compiled.
Contents
What sealing means and how it is enforced
Before Java 17 a class had two choices: open to any subclass, or finalsealedpermits
Sealing is recorded in the class file. The compiler writes a PermittedSubclassesjavap -vClass.getPermittedSubclasses()
- At compile time,
rejects any class that extends the sealed type without being listed, and any listed class that does not say how its own branch continues.javac - At class loading, the JVM rejects a class whose superclass or interface is sealed and does not list it, with
. So the restriction also holds for code compiled separately or generated at run time.IncompatibleClassChangeError
Because the set of subtypes is known, a switchdefault
| Modifier | Used on | Meaning | Best for |
|---|---|---|---|
sealed ... permits A, B | The parent, or a subtype | Only the listed types may extend it | Closed sets of alternatives |
final | A permitted class | No further subclasses (records and enums are implicitly final) | Leaf cases |
non-sealed | A permitted class or interface | Open again: any class may extend it | An extension point inside a closed set |
History: sealed classes were previewed in Java 15 (JEP 360) and Java 16 (JEP 397) and became standard in Java 17 (JEP 409). Exhaustive pattern-matching switches over them became standard in Java 21 (JEP 441). Sealing itself needs Java 17, the switches below need Java 21, and all outputs were captured on JDK 21.
Declaring a hierarchy with final, sealed and non-sealed
The program builds one branch of each kind: CarTruckDumpTruckBikeTricycle
import java.util.Arrays;
public class SealedHierarchy {
// Only the three listed classes may extend Vehicle
abstract static sealed class Vehicle permits Car, Truck, Bike {
abstract int wheels();
}
// final: the branch stops here
static final class Car extends Vehicle {
int wheels() {
return 4;
}
}
// sealed: the branch continues, but only with the listed subclasses
static sealed class Truck extends Vehicle permits DumpTruck {
int wheels() {
return 6;
}
}
static final class DumpTruck extends Truck {
@Override
int wheels() {
return 10;
}
}
// non-sealed: anyone may extend this branch again
static non-sealed class Bike extends Vehicle {
int wheels() {
return 2;
}
}
static class Tricycle extends Bike {
@Override
int wheels() {
return 3;
}
}
static String names(Class<?>[] classes) {
return Arrays.toString(Arrays.stream(classes).map(Class::getSimpleName).toArray());
}
public static void main(String[] args) {
for (Class<?> c : new Class<?>[] {Vehicle.class, Truck.class, Bike.class, Car.class}) {
System.out.printf("%-8s sealed=%-5b permitted=%s%n", c.getSimpleName(), c.isSealed(),
c.isSealed() ? names(c.getPermittedSubclasses()) : "-");
}
Vehicle[] fleet = {new Car(), new DumpTruck(), new Tricycle(), new Bike() {
// An anonymous subclass is allowed only below the non-sealed Bike
}};
int total = 0;
for (Vehicle v : fleet) {
total += v.wheels();
}
System.out.println("total wheels in the fleet: " + total);
}
}
Output:
Vehicle sealed=true permitted=[Car, Truck, Bike]
Truck sealed=true permitted=[DumpTruck]
Bike sealed=false permitted=-
Car sealed=false permitted=-
total wheels in the fleet: 19
- Only
andVehicle reportTruck .sealed=true is final, which is a different property, andCar is false for it.isSealed reportsBike becausesealed=false really does reopen the branch. That is whynon-sealed and the anonymousTricycle subclass compile, while an anonymous subclass ofBike would not.Vehicle- The total is 19. Sealing restricts who may extend a type, not who may use it: any code can hold a
and callVehicle .wheels()
What the compiler checks
To show the real messages, the program compiles four small sources in memory with the javax.toolsShape
import java.net.URI;
import java.util.List;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
// Compiles small sources in memory and prints what javac says about them
public class CompilerChecks {
static void compile(String label, String code) {
JavaFileObject file = new SimpleJavaFileObject(URI.create("string:///Demo.java"),
JavaFileObject.Kind.SOURCE) {
@Override
public CharSequence getCharContent(boolean ignore) {
return code;
}
};
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diags = new DiagnosticCollector<>();
boolean ok = javac.getTask(null, null, diags, List.of("-d", System.getProperty(
"java.io.tmpdir")), null, List.of(file)).call();
System.out.println(label + ": " + (ok ? "compiles" : "error"));
diags.getDiagnostics().forEach(d -> System.out.println(" " + d.getMessage(null)));
}
public static void main(String[] args) {
String shapes = """
sealed interface Shape permits Circle, Square, Hexagon {}
record Circle(double r) implements Shape {}
record Square(double side) implements Shape {}
record Hexagon(double side) implements Shape {}
""";
compile("switch handles all three shapes", shapes + """
class Demo {
static String name(Shape s) {
return switch (s) {
case Circle c -> "circle";
case Square q -> "square";
case Hexagon h -> "hexagon";
};
}
}
""");
compile("switch forgets Hexagon", shapes + """
class Demo {
static String name(Shape s) {
return switch (s) {
case Circle c -> "circle";
case Square q -> "square";
};
}
}
""");
compile("class outside the permits list", shapes + """
class Demo {}
record Triangle(double b, double h) implements Shape {}
""");
compile("permitted subclass without a modifier", """
sealed class Animal permits Dog {}
class Dog extends Animal {}
class Demo {}
""");
}
}
Output (each message is javac's own text):
switch handles all three shapes: compiles
switch forgets Hexagon: error
the switch expression does not cover all possible input values
class outside the permits list: error
class is not allowed to extend sealed class: Shape (as it is not listed in its 'permits' clause)
permitted subclass without a modifier: error
sealed, non-sealed or final modifiers expected
- A switch with a case for all three shapes compiles with no
, because thedefault clause says nothing else can implementpermits .Shape - Without the
case it fails with "does not cover all possible input values". This is the main payoff: add a type toHexagon and every switch that forgot it fails to compile, instead of silently reaching apermits branch at run time.default - A class that is not listed cannot implement the interface, and the message names the
clause.permits - A permitted class with none of the three modifiers is rejected with "sealed, non-sealed or final modifiers expected". Records need no modifier because they are implicitly final.
Sealed types compared with enums
An enum and a sealed interface both describe a closed set, but of different things. The program models payment methods both ways, using a card, a bank transfer and cash because each needs different data. It also leaves out the permits
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
public class EnumVsSealed {
// An enum: a fixed set of INSTANCES, all with the same fields
enum Method {
CARD, BANK_TRANSFER, CASH
}
// A sealed interface: a fixed set of TYPES, each with its own data.
// No permits clause: the compiler infers it from the subtypes in this file
sealed interface Payment {
BigDecimal amount();
}
record Card(BigDecimal amount, String last4) implements Payment {
}
record BankTransfer(BigDecimal amount, String iban) implements Payment {
}
record Cash(BigDecimal amount) implements Payment {
}
static BigDecimal fee(Method m, BigDecimal amount) {
return switch (m) { // exhaustive over the enum constants
case CARD -> amount.multiply(new BigDecimal("0.029"));
case BANK_TRANSFER -> new BigDecimal("0.50");
case CASH -> BigDecimal.ZERO;
};
}
static String describe(Payment p) {
return switch (p) { // exhaustive over the permitted types
case Card c -> "card ending " + c.last4();
case BankTransfer t -> "transfer from " + t.iban().substring(0, 4) + "...";
case Cash c -> "cash";
};
}
public static void main(String[] args) {
System.out.println("enum constants: " + Arrays.toString(Method.values()));
System.out.println("card fee on 100: " + fee(Method.CARD, new BigDecimal("100")));
System.out.println("inferred permits: " + Arrays.stream(
Payment.class.getPermittedSubclasses()).map(Class::getSimpleName).toList());
List<Payment> payments = List.of(
new Card(new BigDecimal("25.00"), "4242"),
new BankTransfer(new BigDecimal("900.00"), "DE89370400440532013000"),
new Cash(new BigDecimal("12.50")));
for (Payment p : payments) {
System.out.printf("%-22s %8s%n", describe(p), p.amount());
}
}
}
Output:
enum constants: [CARD, BANK_TRANSFER, CASH]
card fee on 100: 2.900
inferred permits: [Card, BankTransfer, Cash]
card ending 4242 25.00
transfer from DE89... 900.00
cash 12.50
- The enum has exactly three instances, and every one has the same fields. It suits labels and states:
can select a fee rule (2.9% of 100 is 2.900), but it cannot carry the card's last four digits.CARD - The sealed interface has exactly three types, and each can have any number of instances with its own data: a card has
, a transfer has an IBAN, cash has neither.last4 - The
clause was omitted, andpermits still listsgetPermittedSubclasses ,Card andBankTransfer . When all subtypes are in the same source file, the compiler infers the list in declaration order.Cash - Both switches are exhaustive without
. Switching on enum constants has been checked this way since switch expressions arrived in Java 14; switching on sealed types needs the type patterns of Java 21.default
Enums can implement a sealed interface too, which mixes both: sealed interface Op permits BinaryOp, UnaryOpenum BinaryOp implements Op { PLUS, MINUS }
Modeling a result type
A sealed interface with record cases models "one of these, and nothing else". The ResultOkErr
import java.util.List;
public class ResultType {
// A value that is either a success or a failure, and nothing else
sealed interface Result<T> permits Ok, Err {
}
record Ok<T>(T value) implements Result<T> {
}
record Err<T>(String message) implements Result<T> {
}
static Result<Integer> parsePort(String text) {
try {
int port = Integer.parseInt(text.trim());
if (port < 1 || port > 65535) {
return new Err<>(port + " is outside 1-65535");
}
return new Ok<>(port);
} catch (NumberFormatException e) {
return new Err<>("'" + text + "' is not a number");
}
}
public static void main(String[] args) {
for (String input : List.of("8080", " 443 ", "70000", "http")) {
String message = switch (parsePort(input)) {
case Ok<Integer>(Integer port) -> "port " + port;
case Err<Integer>(String why) -> "error: " + why;
};
System.out.printf("%-8s -> %s%n", "[" + input + "]", message);
}
}
}
Output:
[8080] -> port 8080
[ 443 ] -> port 443
[70000] -> error: 70000 is outside 1-65535
[http] -> error: 'http' is not a number
" 443 " was accepted because parsePortErrmaindefault
Changing a sealed hierarchy after clients are compiled
A sealed hierarchy is a promise to every client, and changing it has effects even on code that is not recompiled. The program compiles version 1 of two small libraries into a temporary directory, then compiles version 2 of only some files, and loads the mix with a class loader. One change adds a new shape; the other seals an interface that an existing class already implements.
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
// Compiles code in two steps, changes the sealed type in between, and runs the old classes
public class SeparateCompilation {
static final JavaCompiler JAVAC = ToolProvider.getSystemJavaCompiler();
public static void main(String[] args) throws Exception {
Path dir = Files.createTempDirectory("sealed");
// Version 1: Shape permits Circle and Square; Report switches over both
write(dir, "Shape.java", "public sealed interface Shape permits Circle, Square {}");
write(dir, "Circle.java", "public record Circle(double r) implements Shape {}");
write(dir, "Square.java", "public record Square(double s) implements Shape {}");
write(dir, "Report.java", """
public class Report {
public static String name(Shape s) {
return switch (s) {
case Circle c -> "circle";
case Square q -> "square";
};
}
}""");
write(dir, "Legacy.java", "public final class Legacy implements Old {}");
write(dir, "Old.java", "public interface Old {}");
compile(dir, "Shape.java", "Circle.java", "Square.java", "Report.java",
"Old.java", "Legacy.java");
System.out.println("version 1 compiled: Report knows Circle and Square");
// Version 2: a new shape is added, Report is NOT recompiled
write(dir, "Shape.java", "public sealed interface Shape permits Circle, Square, Tri {}");
write(dir, "Tri.java", "public record Tri(double b, double h) implements Shape {}");
// Old becomes sealed without listing Legacy, Legacy is NOT recompiled
write(dir, "Old.java", "public sealed interface Old permits Newer {}");
write(dir, "Newer.java", "public final class Newer implements Old {}");
compile(dir, "Shape.java", "Tri.java", "Old.java", "Newer.java");
System.out.println("version 2 compiled: Tri added, Old sealed");
try (URLClassLoader loader = new URLClassLoader(new URL[] {dir.toUri().toURL()})) {
Method name = loader.loadClass("Report").getMethod("name",
loader.loadClass("Shape"));
Object circle = loader.loadClass("Circle").getConstructors()[0].newInstance(1.0);
Object tri = loader.loadClass("Tri").getConstructors()[0].newInstance(1.0, 2.0);
System.out.println("old switch, Circle: " + name.invoke(null, circle));
try {
name.invoke(null, tri);
} catch (java.lang.reflect.InvocationTargetException e) {
System.out.println("old switch, Tri: " + e.getCause());
}
try {
loader.loadClass("Legacy");
} catch (IncompatibleClassChangeError e) {
System.out.println("loading Legacy: " + e.getClass().getSimpleName()
+ ": " + e.getMessage());
}
}
}
static void write(Path dir, String file, String code) throws IOException {
Files.writeString(dir.resolve(file), code);
}
static void compile(Path dir, String... files) {
List<String> argv = new ArrayList<>(List.of("-d", dir.toString(), "-cp", dir.toString()));
for (String f : files) {
argv.add(dir.resolve(f).toString());
}
int rc = JAVAC.run(null, null, null, argv.toArray(new String[0]));
if (rc != 0) {
throw new IllegalStateException("javac failed");
}
}
}
Output:
version 1 compiled: Report knows Circle and Square
version 2 compiled: Tri added, Old sealed
old switch, Circle: circle
old switch, Tri: java.lang.MatchException
loading Legacy: IncompatibleClassChangeError: class Legacy cannot implement sealed interface Old
- The old
class still handles aReport . Given aCircle , which did not exist when it was compiled, its exhaustive switch threwTri . The compiler inserts this hidden default into every exhaustive pattern switch without aMatchException , so an unexpected subtype fails loudly instead of being ignored.default - Loading
failed withLegacy : "class Legacy cannot implement sealed interface Old". The JVM checks theIncompatibleClassChangeError attribute when it loads a subclass, not onlyPermittedSubclasses .javac - So adding a permitted subtype is a breaking change for anyone who switches over the type, and sealing a published interface breaks every existing implementation. For a public library API, seal from the start or not at all.
Rules and constraints
- Permitted subclasses must be in the same module as the sealed class. In code that is not in a named module, they must be in the same package.
- The
clause may be left out when every subclass is declared in the same source file, as shown above.permits - Each permitted subclass must directly extend or implement the sealed type, and must be
,final orsealed . Records and enums are implicitlynon-sealed .final - Interfaces can be sealed. A permitted sub-interface uses
orsealed , since interfaces cannot benon-sealed .final - Anonymous classes and lambdas cannot implement a sealed type, because they have no name to list. A sealed functional interface therefore cannot be implemented with a lambda.
- A
subtype keeps exhaustiveness for the parent: a switch that has a case fornon-sealed coversBike and every future subclass ofTricycle .Bike
Which one to use
| Situation | Use |
|---|---|
| A fixed set of values with the same fields (states, labels, units) | enum |
| A fixed set of alternatives, each with its own data | Sealed interface with record implementations |
| A closed set where one branch must stay extensible | Sealed parent with a non-sealed |
| A class nobody should extend | final |
| A public library interface users implement | Neither: keep it open, because sealing it later breaks them |
| A result that is either a value or an error | Sealed ResultOkErr |
For the switch side of sealed types, see