Sealed classes and interfaces
suggest changeBefore Java 17 a class could be extended by any other class unless it was final, and an interface could be implemented by anyone. Nothing in between existed: you could not say "a Shape is a Circle, a Rectangle or a Polygon, and nothing else".
A sealed class or interface lists the classes that may extend or implement it. The compiler and the JVM enforce that list, which gives you:
- a closed set of alternatives you control, while the subtypes can still carry different data and behaviour
switchover the type that the compiler can check for exhaustiveness, with nodefaultbranch- a hierarchy that documents itself: the declaration tells readers every possible case
Sealed classes were a preview in Java 15 and 16 and became a standard feature in Java 17 (JEP 409). Everything in this article works in JDK 17 and later, except pattern-matching switch and record patterns, which need Java 21. The examples are single files you run with java Example.java. Output is from JDK 25.
Related articles: Pattern Matching and Records show sealed types used for exhaustive switch. Using final to restrict inheritance and overriding covers final.
Declaring a sealed hierarchy
Add the sealed modifier and list the allowed subtypes after permits. The permits clause goes after extends and implements:
public sealed interface Shape permits Circle, Rectangle, Polygon {}
public abstract sealed class Account permits Checking, Savings {}
public sealed class Rectangle implements Shape permits Square {}
Every permitted subclass must say how it continues the hierarchy, with exactly one of three modifiers:
final: the subclass can't be extended. Records and enums are implicitlyfinal, so they need nothing.sealed: the subclass is itself sealed, with its ownpermitslist.non-sealed: the subclass is open again and anyone may extend it. This is the only hyphenated keyword in Java.
Here is a hierarchy that uses all three:
public class Shapes {
sealed interface Shape permits Circle, Rectangle, Polygon {}
// final: no further subclasses
static final class Circle implements Shape {
final double r;
Circle(double r) { this.r = r; }
}
// sealed: has its own closed list of subclasses
static sealed class Rectangle implements Shape permits Square {
final double w, h;
Rectangle(double w, double h) { this.w = w; this.h = h; }
}
static final class Square extends Rectangle {
Square(double side) { super(side, side); }
}
// non-sealed: open again, anyone may extend it
static non-sealed class Polygon implements Shape {
final int sides;
Polygon(int sides) { this.sides = sides; }
}
static class Hexagon extends Polygon {
Hexagon() { super(6); }
}
static String describe(Shape s) {
return switch (s) {
case Circle c -> "circle r=" + c.r;
case Square sq -> "square " + sq.w;
case Rectangle r -> "rectangle " + r.w + "x" + r.h;
case Polygon p -> "polygon with " + p.sides + " sides";
};
}
public static void main(String[] args) {
Shape[] shapes = { new Circle(1), new Rectangle(2, 3), new Square(4), new Hexagon() };
for (Shape s : shapes) System.out.println(describe(s));
}
}
circle r=1.0
rectangle 2.0x3.0
square 4.0
polygon with 6 sides
The switch in describe has no default, yet it compiles: Shape can only be a Circle, a Rectangle (which includes Square) or a Polygon. Hexagon is covered by case Polygon p, because non-sealed opens the hierarchy below Polygon but not beside it. Square must come before Rectangle, or the compiler reports "this case label is dominated by a preceding case label".
non-sealed is how you leave an extension point in an otherwise closed hierarchy. A switch still only has to handle Polygon, whatever subclasses other code adds.
What the compiler rejects
A subclass that leaves out the modifier, and a class that isn't in the permits list, are both errors:
sealed class Vehicle permits Car, Truck {}
final class Car extends Vehicle {}
class Truck extends Vehicle {} // missing final / sealed / non-sealed
final class Bike extends Vehicle {} // not in permits
Vehicle.java:5: error: sealed, non-sealed or final modifiers expected
class Truck extends Vehicle {} // missing final / sealed / non-sealed
^
Vehicle.java:7: error: class is not allowed to extend sealed class: Vehicle (as it is not listed in its 'permits' clause)
final class Bike extends Vehicle {} // not in permits
^
2 errors
Anonymous and local classes can't extend a sealed type either, since they can't appear in a permits list:
sealed interface Animal permits Dog {}
final class Dog implements Animal {}
public class Base {
public static void main(String[] args) {
Animal a = new Animal() {}; // anonymous class
class Cat implements Animal {} // local class
}
}
Base.java:6: error: anonymous classes must not extend sealed classes
Animal a = new Animal() {}; // anonymous class
^
Base.java:7: error: local classes must not extend sealed classes
class Cat implements Animal {} // local class
^
2 errors
For the same reason a sealed interface is never a functional interface, even with a single abstract method, so you can't implement it with a lambda:
public class Fn {
sealed interface Op permits Add {
int apply(int a, int b);
}
record Add() implements Op {
public int apply(int a, int b) { return a + b; }
}
public static void main(String[] args) {
Op mul = (a, b) -> a * b;
}
}
Fn.java:9: error: incompatible types: Op is not a functional interface
Op mul = (a, b) -> a * b;
^
1 error
The checks aren't only done by javac. The class file stores the list in a PermittedSubclasses attribute, and the JVM refuses to load a class that tries to extend a sealed class it isn't listed in, so a hand-crafted or separately compiled subclass can't get around the rule.
Where permitted subclasses may live
The sealed class and its permitted subclasses must be able to see each other at compile time, and they must be in the same place:
- in the same module, if the sealed class is in a named module (any packages of that module)
- in the same package, if the code is in the unnamed module, which is the case for ordinary classpath code
So with a plain classpath build, this split across two packages fails:
// src/com/example/shapes/Shape.java
package com.example.shapes;
import com.example.shapes.impl.Circle;
public sealed interface Shape permits Circle {}
// src/com/example/shapes/impl/Circle.java
package com.example.shapes.impl;
import com.example.shapes.Shape;
public record Circle(double radius) implements Shape {}
$ javac -d out src/com/example/shapes/Shape.java src/com/example/shapes/impl/Circle.java
src\com\example\shapes\Shape.java:5: error: class Shape in unnamed module cannot extend a sealed class in a different package
public sealed interface Shape permits Circle {}
^
1 error
Add a module-info.java that puts both packages in one module and the same files compile:
// src/module-info.java
module com.example.shapes {
exports com.example.shapes;
exports com.example.shapes.impl;
}
$ javac -d out src/module-info.java src/com/example/shapes/Shape.java src/com/example/shapes/impl/Circle.java
The rule exists because a sealed hierarchy is meant to be maintained by one team as one unit. See Modules for module basics.
Leaving out permits
When the sealed class and all its subclasses are declared in the same source file, you can leave out permits and the compiler infers the list from the subclasses in that file. Nesting the subtypes inside the sealed interface is a common way to do this:
sealed interface Expr {
record Num(int value) implements Expr {}
record Add(Expr left, Expr right) implements Expr {}
}
Spell out permits when the subtypes live in other files (it is required then), or when you want the list to be visible at the top of a large file.
Records and enums as subtypes
Records are implicitly final, which makes them the most common permitted subtype: one record per case, each holding just the data for that case. Enums are implicitly final too (or implicitly sealed, see below), so an enum can implement a sealed interface. That lets you mix constants for cases without data with records for cases that have data:
import java.util.List;
public class Commands {
sealed interface Command permits Simple, Move, Say {}
// fixed commands without data: enum constants
enum Simple implements Command { STOP, JUMP }
// commands with data: records
record Move(int dx, int dy) implements Command {}
record Say(String text) implements Command {}
static String run(Command c) {
return switch (c) {
case Simple.STOP -> "stopping";
case Simple.JUMP -> "jumping";
case Move(int dx, int dy) when dx == 0 && dy == 0 -> "staying put";
case Move(int dx, int dy) -> "moving by " + dx + "," + dy;
case Say(String text) -> "saying '" + text + "'";
};
}
enum Op {
PLUS { int apply(int a, int b) { return a + b; } },
TIMES { int apply(int a, int b) { return a * b; } };
abstract int apply(int a, int b);
}
public static void main(String[] args) {
List<Command> script = List.of(new Move(1, 2), new Say("hi"), Simple.JUMP, new Move(0, 0), Simple.STOP);
script.forEach(c -> System.out.println(run(c)));
System.out.println(Simple.class.isSealed() + " " + Op.class.isSealed());
System.out.println(java.util.Arrays.toString(Op.class.getPermittedSubclasses()));
}
}
moving by 1,2
saying 'hi'
jumping
staying put
stopping
false true
[class Commands$Op$1, class Commands$Op$2]
- Since Java 21 a
caselabel can be a qualified enum constant such asSimple.STOP, even when the selector's type is the sealed interface. Covering every constant counts toward exhaustiveness. - A plain enum is
final. An enum whose constants have bodies, likeOp, is compiled as a sealed class whose permitted subclasses are the anonymous classes of its constants. See Enum constant specific body.
Exhaustive switch
The main payoff of sealing is that the compiler knows every case. A switch expression or pattern switch over a sealed type compiles without default when it handles every permitted subtype, and fails when it doesn't:
Checkout.java:3: error: the switch expression does not cover all possible input values
return switch (p) {
^
1 error
Prefer listing every case over adding default. With default, adding a new subtype compiles silently and the new case falls into the catch-all. Without it, every switch that needs updating becomes a compile error. Pattern Matching and Records have more examples of exhaustive switches with record patterns and guards.
The compiler uses sealing for casts too. When a cast or instanceof can't possibly succeed, it's an error:
public class Cast {
sealed interface Shape permits Circle {}
final class Circle implements Shape {}
interface Named {}
static void test(Shape s) {
Named n = (Named) s; // Shape's only subtype Circle is final and not Named
}
}
Cast.java:7: error: incompatible types: Shape cannot be converted to Named
Named n = (Named) s; // Shape's only subtype Circle is final and not Named
^
1 error
Without sealed, this cast would compile, because some unknown class could extend Shape and implement Named.
Modelling algebraic data types
A sealed interface with record subtypes is Java's version of an algebraic data type (a "sum of products"), like enum in Rust or a sealed class in Kotlin. Each record is one variant, and functions over the type are switch expressions with one case per variant.
Here is a small expression language with evaluation, printing and simplification:
import java.util.Map;
public class Calc {
sealed interface Expr {
record Num(double value) implements Expr {}
record Var(String name) implements Expr {}
record Neg(Expr operand) implements Expr {}
record Bin(char op, Expr left, Expr right) implements Expr {}
}
static double eval(Expr e, Map<String, Double> env) {
return switch (e) {
case Expr.Num(double v) -> v;
case Expr.Var(String name) -> {
Double v = env.get(name);
if (v == null) throw new IllegalArgumentException("unbound: " + name);
yield v;
}
case Expr.Neg(Expr x) -> -eval(x, env);
case Expr.Bin(char op, Expr l, Expr r) -> {
double a = eval(l, env), b = eval(r, env);
yield switch (op) {
case '+' -> a + b;
case '-' -> a - b;
case '*' -> a * b;
case '/' -> a / b;
default -> throw new IllegalStateException("bad op " + op);
};
}
};
}
static String show(Expr e) {
return switch (e) {
case Expr.Num(double v) -> v == Math.floor(v) ? String.valueOf((long) v) : String.valueOf(v);
case Expr.Var(String name) -> name;
case Expr.Neg(Expr x) -> "-" + show(x);
case Expr.Bin(char op, Expr l, Expr r) -> "(" + show(l) + " " + op + " " + show(r) + ")";
};
}
// x * 1 -> x, x + 0 -> x, x * 0 -> 0, --x -> x
static Expr simplify(Expr e) {
return switch (e) {
case Expr.Neg(Expr x) -> switch (simplify(x)) {
case Expr.Neg(Expr inner) -> inner;
case Expr.Num(double v) -> new Expr.Num(-v);
case Expr s -> new Expr.Neg(s);
};
case Expr.Bin(char op, Expr l, Expr r) -> {
Expr a = simplify(l), b = simplify(r);
if (op == '*' && (isNum(a, 0) || isNum(b, 0))) yield new Expr.Num(0);
if (op == '*' && isNum(b, 1) || op == '+' && isNum(b, 0)) yield a;
if (op == '*' && isNum(a, 1) || op == '+' && isNum(a, 0)) yield b;
yield new Expr.Bin(op, a, b);
}
case Expr.Num n -> n;
case Expr.Var v -> v;
};
}
static boolean isNum(Expr e, double v) {
return e instanceof Expr.Num(double x) && x == v;
}
public static void main(String[] args) {
// (x * 1 + 0) * (y + --3)
Expr e = new Expr.Bin('*',
new Expr.Bin('+', new Expr.Bin('*', new Expr.Var("x"), new Expr.Num(1)), new Expr.Num(0)),
new Expr.Bin('+', new Expr.Var("y"), new Expr.Neg(new Expr.Neg(new Expr.Num(3)))));
Map<String, Double> env = Map.of("x", 2.0, "y", 4.5);
System.out.println(show(e) + " = " + eval(e, env));
Expr s = simplify(e);
System.out.println(show(s) + " = " + eval(s, env));
}
}
(((x * 1) + 0) * (y + --3)) = 15.0
(x * (y + 3)) = 15.0
Compare this with the classic object-oriented design, where Expr would declare abstract eval, show and simplify methods and each subclass would implement all of them:
- Virtual methods make it easy to add a new variant (one new class) and hard to add a new operation (touch every class).
- Sealed types with
switchmake it easy to add a new operation (one new method) and hard to add a variant (touch everyswitch, but the compiler finds them for you).
Use sealed types when the set of variants is stable and the operations keep growing, which is typical for ASTs, protocol messages, events, commands, state machines and result types like Ok | Err. Use virtual methods when the operations are fixed and third parties need to add variants. The two mix fine: a sealed interface can still declare methods that each record implements.
Sealed vs. enum
Both describe a fixed set of alternatives. The difference is whether the alternatives are values or types:
| enum | sealed interface + records | |
|---|---|---|
| each case is | a single instance | a type with any number of instances |
| per-case data | same fields for every constant | each record has its own components |
| iterate over all cases | values(), EnumSet, EnumMap |
only by reflection (getPermittedSubclasses) |
serialization, ordinal, name |
built in | you write it |
exhaustive switch |
yes | yes |
Use an enum when the cases are constants: days of the week, HTTP methods, log levels. Use a sealed hierarchy when cases carry different data: Move(dx, dy) and Say(text) don't fit into one set of enum fields. As shown above, an enum can be one of the permitted subtypes when only some cases are constants.
Reflection
Class has two methods for sealed types, added in Java 17:
isSealed()returnstruefor a sealed class or interface.getPermittedSubclasses()returns the permitted subtypes as aClass<?>[], ornullif the class isn't sealed.
This walks a hierarchy and prints it. The permits list of Expr is inferred, since everything is in one file:
import java.util.Arrays;
public class Reflect {
sealed interface Expr {}
record Num(int value) implements Expr {}
record Add(Expr left, Expr right) implements Expr {}
static non-sealed class Custom implements Expr {}
enum Const implements Expr { ZERO, ONE }
static void printTree(Class<?> c, String indent) {
String kind = c.isSealed() ? "sealed"
: java.lang.reflect.Modifier.isFinal(c.getModifiers()) ? "final"
: "open";
System.out.println(indent + c.getSimpleName() + " (" + kind + ")");
if (c.isSealed()) {
for (Class<?> sub : c.getPermittedSubclasses()) {
printTree(sub, indent + " ");
}
}
}
public static void main(String[] args) {
printTree(Expr.class, "");
System.out.println(Arrays.toString(Expr.class.getPermittedSubclasses()));
System.out.println(String.class.isSealed() + " " + String.class.getPermittedSubclasses());
}
}
Expr (sealed)
Num (final)
Add (final)
Custom (open)
Const (final)
[class Reflect$Num, class Reflect$Add, class Reflect$Custom, class Reflect$Const]
false null
Serialization libraries use this to discover the subtypes of a polymorphic type without a hand-maintained list. javap -v shows the same list as the PermittedSubclasses attribute of the class file.
Evolving a sealed API
Sealing is a promise to your users that the list of subtypes is complete, so they can write exhaustive switches against it. That makes the list part of your public API:
- Adding a permitted subtype breaks source compatibility. Client code with an exhaustive
switchstops compiling until it handles the new case. - Removing a subtype, or changing
non-sealedtosealedorfinal, breaks clients that use or extend it. - Removing
sealedfrom a type lets anyone extend it, but exhaustive switches over that type stop compiling because the set of subtypes is no longer closed.
Binary compatibility is a different story. Code compiled against the old version keeps running, until a switch meets a subtype it didn't know about. The compiler adds a hidden fallback branch to every exhaustive switch over a sealed type that throws MatchException.
Here is version 1 of a library:
// v1/Payment.java
import java.util.List;
public sealed interface Payment permits Card, Cash {
static List<Payment> samples() {
return List.of(new Card("4111"), new Cash());
}
}
record Card(String number) implements Payment {}
record Cash() implements Payment {}
and a client compiled against it:
// Checkout.java
public class Checkout {
static String fee(Payment p) {
return switch (p) {
case Card c -> "card: 1.5% fee";
case Cash c -> "cash: no fee";
};
}
public static void main(String[] args) {
for (Payment p : Payment.samples()) System.out.println(fee(p));
}
}
Version 2 of the library adds record Voucher(String code) implements Payment {} to permits and to samples(). Swap the library jar without recompiling the client:
$ javac -d lib v1/Payment.java
$ javac -cp lib -d app Checkout.java
$ java -cp "lib;app" Checkout
card: 1.5% fee
cash: no fee
$ javac -d lib v2/Payment.java
$ java -cp "lib;app" Checkout
card: 1.5% fee
cash: no fee
Exception in thread "main" java.lang.MatchException
at Checkout.fee(Checkout.java:3)
at Checkout.main(Checkout.java:10)
$ javac -cp lib -d app Checkout.java
Checkout.java:3: error: the switch expression does not cover all possible input values
return switch (p) {
^
1 error
(On Linux and macOS, separate classpath entries with : instead of ;.)
Some guidelines that follow from this:
- Seal types whose variants are part of the domain and won't change often. If you expect to add cases, say so in the docs, or use
non-sealedfor an extension point. - Treat a new permitted subtype as a breaking change and release it in a major version.
- Inside a single application or module, where everything is compiled together, adding a case is cheap: the compiler lists every
switchto update. - In client code, a
defaultbranch trades the compile error for silent handling. Use one only if you really have a sensible fallback for future cases.
Before Java 17
Older code fakes a closed hierarchy with a package-private constructor in an abstract class, so only classes in the same package can call super(). That stops outside subclasses, but the compiler doesn't know the set is closed, so every switch or instanceof chain still needs a fallback branch, and the list of subtypes isn't written down anywhere. On Java 17 and later, replace it with sealed and permits.
Summary
sealedwithpermitsrestricts which classes may extend a class or implement an interface. It's standard since Java 17 (JEP 409).- Each permitted subclass must be
final,sealedornon-sealed. Records and enums are implicitlyfinal. non-sealedreopens one branch of the hierarchy for extension, without affecting exhaustiveness of the parent.- Permitted subclasses must be in the same module, or in the same package when the code is on the classpath.
- When all subtypes are in the same file,
permitscan be left out. - Anonymous classes, local classes and lambdas can't implement a sealed type.
- A
switchthat covers every permitted subtype needs nodefault. Leave it out, so adding a case shows every place to update. - A sealed interface with records models algebraic data types. Use an enum when the cases are plain constants.
Class.isSealed()andgetPermittedSubclasses()expose the hierarchy at runtime.- Adding a permitted subtype breaks clients' exhaustive switches at compile time, and old compiled code throws
MatchExceptionwhen it meets the new case.