Java Sealed Classes and Interfaces: Controlling Inheritance
Java sealed classes and interfaces (final since Java 17) let you list exactly which classes may extend a type. Learn sealed, permits, final and non-sealed, the placement rules, exhaustive switch without default, records and enums in sealed hierarchies, and when to choose sealed types.
kvi5hnuCode Sprout team member8 min readOn this page
So far a class had two settings: open to every subclass, or final and closed to all. Often neither fits. You want to say "exactly these subclasses, and nothing else". That's what sealed classes provide. They were a preview feature in Java 15 and 16 and became final in Java 17.
The Problem: Hierarchies That Should Be Closed
Suppose you're writing a chess engine. The rules of chess fix the kinds of pieces: king, queen, rook, bishop, knight and pawn, six and no more. A natural model is an abstract class Piece with six subclasses, each declared final so nobody can extend them:
public abstract class Piece { /* colour, position, ... */ }
public final class King extends Piece { . . . }
public final class Queen extends Piece { . . . }
. . .
final on the subclasses doesn't prevent a seventh direct subclass of Piece, though. And code like this quietly assumes there isn't one:
Piece p = . . .;
if (p instanceof King k) . . .
else if (p instanceof Queen q) . . .
else if (p instanceof Rook r) . . .
else if (p instanceof Bishop b) . . .
else if (p instanceof Knight n) . . .
else . . . // must be a Pawn
Every branch reflects knowledge of the complete list. If someone added a new piece type somewhere else, the final else would treat it as a pawn without any warning. The engine's authors want to own this list; nobody else should be able to extend it.
Many domains look like this: payment methods (card, bank transfer, wallet), shapes in a drawing program, expression trees in a calculator, success/failure results, the states of an order. In each case, the set of variants is part of the design.
Declaring a Sealed Type
A sealed class or interface lists the classes that may directly extend or implement it in a permits clause:
public abstract sealed class Piece
permits King, Queen, Rook, Bishop, Knight, Pawn {
. . .
}
Defining a subclass that isn't listed is a compile-time error:
public class Archbishop extends Piece { . . . }
// error: class is not allowed to extend sealed class: Piece (as it is not listed in its 'permits' clause)
Standard chess has no archbishop, so the error is exactly what you want: the type system now enforces a rule of the domain.
Interfaces can be sealed in exactly the same way. That's often the more flexible choice, because records and enums can implement interfaces but can't extend classes:
sealed interface Shape permits Circle, Rectangle, Square, Point { }

Rules for Permitted Subclasses
Every permitted subclass declares how it continues
A direct subclass of a sealed type must say whether the hierarchy continues below it, using exactly one of these modifiers:
| Modifier | Meaning |
|---|---|
final | No further subclasses. (Records and enums are implicitly final.) |
sealed | Further subclasses, but only the ones it permits in turn |
non-sealed | Open again: anyone may extend it |
Without one of them, you get error: sealed, non-sealed or final modifiers expected.
A permitted subclass doesn't have to be final. Exhaustiveness checking only cares about the direct subtypes, and each of them may continue the hierarchy in a controlled way. Queen, rook and bishop all move any distance along lines, so the chess hierarchy could group them under a sealed intermediate class:
public abstract sealed class Piece permits King, Knight, Pawn, Slider { . . . }
public abstract sealed class Slider extends Piece
permits Queen, Rook, Bishop { . . . }
And non-sealed? It fits when the kinds are fixed but one kind should be open to customization. Think of a small UI toolkit whose layout code understands exactly three widget kinds, while applications may build their own containers:
public abstract sealed class Widget permits Button, Label, Panel { . . . }
public non-sealed class Panel extends Widget { . . . }
public class ScrollPanel extends Panel { . . . } // fine: Panel is non-sealed
A switch over Widget still has exactly three cases; a ScrollPanel simply arrives in the Panel case.
Where permitted subclasses may live
- The permitted subclasses must be accessible to the sealed class. They can't be private nested classes elsewhere or package-access classes from another package.
- They must be in the same package as the sealed class, or, if you use modules, in the same module.
- You can omit the
permitsclause if all direct subclasses are declared in the same source file. The compiler then infers the list. Since a file can have only one public top-level class, this mostly suits non-public subclasses, or nested classes (see the next part), which can be public.
sealed abstract class Expr { } // permits inferred: Num and Add
final class Num extends Expr { }
final class Add extends Expr { }
The Payoff: Exhaustive switch
An important motivation for sealed types is compile-time checking. Because the compiler knows all direct subtypes, a pattern-matching switch (covered in detail in the next article) can be checked for exhaustiveness, with no default needed:
static double area(Shape s) {
return switch (s) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Rectangle r -> r.width() * r.height();
case Square sq -> sq.side() * sq.side();
case Point p -> 0;
};
}
If you leave out a case, the compiler complains:
error: the switch expression does not cover all possible input values
The real benefit comes later: if someone adds a Triangle to the permits list, every switch that doesn't handle triangles stops compiling and points to the exact spots that need updating. With a default branch, or an open hierarchy, those places would silently do the wrong thing.
A Complete Example
import java.util.List;
import java.util.Locale;
public class Solution {
public static void main(String[] args) {
List<Shape> shapes = List.of(
new Circle(1),
new Rectangle(2, 3),
new Square(2),
new RoundedSquare(2, 0.5),
Point.ORIGIN);
for (Shape s : shapes) {
System.out.printf(Locale.US, "%-13s %-10s area=%.2f%n",
s.getClass().getSimpleName(), s.kind(), area(s));
}
}
// exhaustive: no default needed, because Shape is sealed
static double area(Shape s) {
return switch (s) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Rectangle r -> r.width() * r.height();
case Square sq -> sq.side() * sq.side();
case Point p -> 0;
};
}
}
sealed interface Shape permits Circle, Rectangle, Square, Point {
default String kind() {
return switch (this) {
case Circle c -> "round";
case Rectangle r -> "angular";
case Square sq -> "angular";
case Point p -> "degenerate";
};
}
}
record Circle(double radius) implements Shape { } // records are implicitly final
record Rectangle(double width, double height) implements Shape { }
non-sealed class Square implements Shape { // open again for subclassing
private final double side;
Square(double side) { this.side = side; }
double side() { return side; }
}
class RoundedSquare extends Square { // allowed: Square is non-sealed
private final double cornerRadius;
RoundedSquare(double side, double cornerRadius) { super(side); this.cornerRadius = cornerRadius; }
}
enum Point implements Shape { ORIGIN } // enums are implicitly final
Circle round area=3.14
Rectangle angular area=6.00
Square angular area=4.00
RoundedSquare angular area=4.00
Point degenerate area=0.00
Notice that RoundedSquare is matched by case Square sq: the switch only needs to cover the direct subtypes. The default method kind() in the interface is explained in the interfaces part.
When to Use Sealed Types
| Situation | Choose |
|---|---|
| A fixed set of values (no per-value data) | enum |
| A fixed set of kinds, each with its own data | sealed interface + records |
| A fixed set of kinds, some open for specialization | sealed type with some non-sealed subclasses |
| Anyone should be able to add new kinds (plugins, frameworks) | ordinary interface or abstract class |
Popular uses: result types (sealed interface Result<T> permits Success, Failure), commands and events, AST nodes in compilers, API responses, and state machines. Libraries also seal types to keep the freedom to evolve them. The JDK itself uses sealed hierarchies, for example in the java.lang.constant API.
Common questions
Sealed class or enum?
Use an enum when each alternative is a single, fixed instance without its own data (Roast.LIGHT). Use a sealed hierarchy when the alternatives carry different data, such as Circle(radius) and Rectangle(w, h), or when you need many instances of each. Enums can even be permitted subtypes of a sealed interface.
Can classes in another package be permitted subclasses? Only if the sealed class is in a named module and they are in the same module. On the class path (the unnamed module), all permitted subclasses must be in the same package as the sealed class.
Does sealing work with reflection?
Yes. Class.isSealed() and getPermittedSubclasses() (Java 17) report the hierarchy, and the JVM itself enforces the PermittedSubclasses attribute. A class that isn't listed can't be loaded as a subclass, even if it was compiled separately.
If I add a new permitted subclass, what breaks?
Every pattern switch over the sealed type that has no default stops compiling until it handles the new subtype. That's the point. Already-compiled code that meets the new subtype at runtime throws MatchException. Plan to recompile the code that switches over the hierarchy.
Can a record extend a sealed class? No. Records can't extend any class. They can implement a sealed interface, which is why sealed interfaces with record implementations are the most common modern pattern for algebraic data types.
Summary
- A sealed class or interface restricts its direct subtypes to those named in
permits(or, withoutpermits, those in the same file). Final since Java 17. - Every permitted subtype must be
final,sealedornon-sealed. Records and enums are implicitly final, so sealed interfaces combine well with them. - Permitted subclasses must be in the same package (or module) and accessible.
- The compiler knows all direct subtypes, so a pattern-matching
switchover a sealed type is checked for exhaustiveness withoutdefault, and adding a subtype breaks every incomplete switch at compile time. - Use sealed types for closed domain models, and ordinary types for open, extensible hierarchies.
Practice Questions
What's the difference between making Piece's subclasses final and making Piece sealed?
Final subclasses can't be extended further, but anyone can still add new direct subclasses of Piece. Sealing Piece restricts which classes may extend it at all. The two are complementary.
sealed interface Vehicle permits Car, Truck {} and class Car implements Vehicle {}. Why doesn't Car compile, and what are the fixes?
A permitted subtype must declare final, sealed or non-sealed. Fix it with final class Car, non-sealed class Car (open for extension), sealed class Car permits ..., or make it a record.
Write a sealed interface Payment with records Card(String number), Bank(String iban) and Cash(), plus a method fee(Payment p) using a switch without default.
sealed interface Payment permits Card, Bank, Cash { }
record Card(String number) implements Payment { }
record Bank(String iban) implements Payment { }
record Cash() implements Payment { }
static double fee(Payment p) {
return switch (p) {
case Card c -> 0.30;
case Bank b -> 0.10;
case Cash c -> 0.0;
};
}
Why is omitting default in a switch over a sealed type better than adding one?
Without default, adding a new permitted subtype makes every switch that doesn't handle it a compile error, so you find all the places to update. A default would silently swallow the new case.
When would you mark a permitted subclass non-sealed?
When the kind itself is fixed but users should be able to specialize it, like Panel in the widget hierarchy, which allows ScrollPanel and other custom containers. Code switching over the sealed type still handles it as one case.
Previous: Java Enum Classes: Enumerated Types with Fields and Methods
Next: Java Pattern Matching: switch Patterns, Record Patterns and Guards
Related reading

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.