Sealed Classes
final class that nobody can extend, and an open class that anybody can — and it lets the compiler know every possible subtype. Combined with records and pattern matching in switch (Java 21), sealed types model data with a fixed set of shapes safely and concisely.
Declaring a Sealed Type
Add the sealed modifier and a permits clause naming the allowed direct subtypes. The compiler rejects any other class that tries to extend or implement it.
// A sealed interface lists every permitted implementation; switch can then be exhaustive.
sealed interface Shape permits Circle, Square, Rectangle {}
record Circle(double radius) implements Shape {} // records are implicitly final
record Square(double side) implements Shape {}
record Rectangle(double width, double height) implements Shape {}
class SealedShapes {
static double area(Shape shape) {
return switch (shape) { // no default needed: all cases covered
case Circle c -> Math.PI * c.radius() * c.radius();
case Square s -> s.side() * s.side();
case Rectangle r -> r.width() * r.height();
};
}
public static void main(String[] args) {
for (Shape s : new Shape[] {new Circle(1), new Square(2), new Rectangle(2, 3)}) {
System.out.printf("%s -> %.2f%n", s, area(s));
}
}
}
Output:
Circle[radius=1.0] -> 3.14
Square[side=2.0] -> 4.00
Rectangle[width=2.0, height=3.0] -> 6.00
The Rules for Permitted Subtypes
- Every permitted subtype must directly extend or implement the sealed type.
- Each must be declared
final,sealedornon-sealed, so the hierarchy states how it continues. Records and enums are implicitly final. - Permitted subtypes must be in the same module as the sealed type, or in the same package if the code is not in a named module.
- The
permitsclause may be omitted when all subtypes are declared in the same source file; the compiler then infers the list.
Shaping a Hierarchy
The three modifiers let each branch choose its own policy. A final subclass closes its branch; a sealed subclass restricts it further with its own permits; a non-sealed subclass deliberately reopens its branch to unknown extensions. Reflection exposes the structure through Class.isSealed() and getPermittedSubclasses().
// Each permitted subclass must say how the hierarchy continues: final, sealed or non-sealed.
abstract sealed class Vehicle permits Car, Truck, Bike {
abstract int wheels();
}
final class Car extends Vehicle { // closed: no subclasses
int wheels() { return 4; }
}
sealed class Truck extends Vehicle permits TankTruck { // still restricted
int wheels() { return 6; }
}
final class TankTruck extends Truck {
@Override int wheels() { return 10; }
}
non-sealed class Bike extends Vehicle { // reopened: anyone may extend Bike
int wheels() { return 2; }
}
class ElectricBike extends Bike {} // allowed because Bike is non-sealed
class SealedHierarchy {
public static void main(String[] args) {
Vehicle[] fleet = {new Car(), new TankTruck(), new ElectricBike()};
for (Vehicle v : fleet) {
System.out.println(v.getClass().getSimpleName() + ": " + v.wheels() + " wheels");
}
System.out.println(Vehicle.class.isSealed() + " "
+ java.util.Arrays.toString(Vehicle.class.getPermittedSubclasses()));
}
}
Output:
Car: 4 wheels
TankTruck: 10 wheels
ElectricBike: 2 wheels
true [class Car, class Truck, class Bike]
Why Seal a Type?
Sealing documents and enforces a design decision: these are all the cases. A library can expose an abstract type for callers to use without letting them add implementations it never anticipated. Unlike making the constructor package-private, sealing is visible in the type's declaration and known to the compiler, which enables exhaustive switch.
Exhaustive switch and Record Patterns
Because the compiler knows every subtype of a sealed type, a switch over it can be exhaustive without a default branch, as area shows above. This matters when the hierarchy changes: add a Triangle to permits, and every such switch fails to compile until it handles the new case. A default branch would hide that, so leave it out on purpose. The arrow form case X -> value used here is the switch expression introduced in Switch; a type pattern such as case Circle c both tests the type and binds a variable.
Deconstructing Records
Records, covered in Records, are natural permitted subtypes: they are final and their components are public. Record patterns (Java 21) take a record apart directly in a case, binding its components to variables, and they nest. This small expression evaluator needs no casts, no visitor classes and no default:
// Sealed types plus record patterns model data with a fixed set of shapes.
sealed interface Expr permits Num, Add, Mul, Neg {}
record Num(int value) implements Expr {}
record Add(Expr left, Expr right) implements Expr {}
record Mul(Expr left, Expr right) implements Expr {}
record Neg(Expr operand) implements Expr {}
class ExprEvaluator {
static int eval(Expr e) {
return switch (e) {
case Num(int v) -> v; // record pattern: deconstruct in place
case Add(Expr l, Expr r) -> eval(l) + eval(r);
case Mul(Expr l, Expr r) -> eval(l) * eval(r);
case Neg(Expr inner) -> -eval(inner);
};
}
static String show(Expr e) {
return switch (e) {
case Num(int v) -> Integer.toString(v);
case Add(var l, var r) -> "(" + show(l) + " + " + show(r) + ")";
case Mul(var l, var r) -> show(l) + " * " + show(r);
case Neg(var inner) -> "-" + show(inner);
};
}
public static void main(String[] args) {
Expr e = new Mul(new Add(new Num(2), new Num(3)), new Neg(new Num(4)));
System.out.println(show(e) + " = " + eval(e));
}
}
Output:
(2 + 3) * -4 = -20
This style — a sealed interface of records, processed by exhaustive switch — is sometimes called data-oriented programming. It suits values with a fixed set of variants: syntax trees, protocol messages, results that are either a success or a failure. When new operations are added often, it is very convenient; when new variants are added often by other teams, classic polymorphism through overridden methods (see Abstraction) may fit better.
Practice
Exercises
- Add
Triangleto theShapeexample'spermitsclause without updatingarea, and read the compiler error; then fix it. - Model a payment
Resultas a sealed interface with recordsApproved(String id)andDeclined(String reason), and print a message for each with aswitch. - Extend the expression evaluator with
Div, and use a guarded pattern (case Div(var l, var r) when eval(r) == 0 -> ...) to report division by zero.