Sealed Classes and Interfaces in Java 17
A sealed class or sealed interface restricts which other classes may extend or implement it. You list the allowed subtypes with permits. Sealed types were previewed in Java 15 and 16 and became a standard feature in Java 17 (JEP 409).
This tutorial explains the problem sealed types solve, the rules for permitted subclasses, and how they work together with records and pattern matching.
1. Why Are Sealed Classes Needed?
Before Java 17 you could only make a class final (nobody may extend it) or leave it open (anybody may). Many domains have a fixed set of variants, such as vehicle types or payment states. Sealed types let you say "exactly these subtypes and no others", which documents the design and lets the compiler check code that handles every case.
2. Syntax and Rules
public sealed interface Vehicle permits Car, Truck, Bike { }
public record Car(int seats) implements Vehicle { } // implicitly final
public final class Truck implements Vehicle { } // final
public non-sealed class Bike implements Vehicle { } // open again
- Every permitted subclass must be
final,sealedornon-sealed. - Permitted subclasses must be in the same module, or in the same package if you do not use modules.
- If all subclasses are in the same source file, the
permitsclause can be omitted; the compiler infers it. - A class not listed in
permitscannot extend the sealed type.
3. Practical Examples
Example 1: A sealed interface with records
public class SealedVehicles {
// Only Car, Truck and Bike may implement Vehicle
sealed interface Vehicle permits Car, Truck, Bike { }
record Car(int seats) implements Vehicle { } // records are implicitly final
record Truck(double loadTonnes) implements Vehicle { }
record Bike() implements Vehicle { }
// Toll rules can rely on the closed set of vehicle types
static int toll(Vehicle v) {
if (v instanceof Car c) {
return c.seats() > 5 ? 120 : 80;
} else if (v instanceof Truck t) {
return 200 + (int) (t.loadTonnes() * 25);
} else if (v instanceof Bike) {
return 20;
}
throw new AssertionError("impossible: Vehicle is sealed");
}
public static void main(String[] args) {
Vehicle[] queue = { new Car(4), new Car(7), new Truck(8.5), new Bike() };
for (Vehicle v : queue) {
System.out.println(v + " -> toll " + toll(v));
}
}
}
Car[seats=4] -> toll 80 Car[seats=7] -> toll 120 Truck[loadTonnes=8.5] -> toll 412 Bike[] -> toll 20
Because Vehicle is sealed, the three instanceof branches cover every possible type. In Java 21 this becomes a switch that the compiler checks for completeness.
Example 2: final, sealed and non-sealed subclasses
public class SealedClassHierarchy {
// A sealed abstract class
static abstract sealed class Account permits Savings, Current, Loan { }
static final class Savings extends Account { } // final: closes this branch
static sealed class Current extends Account permits Overdraft { } // sealed: further restricted
static final class Overdraft extends Current { }
static non-sealed class Loan extends Account { } // non-sealed: open again
static class HomeLoan extends Loan { } // anyone may extend Loan
public static void main(String[] args) {
System.out.println("Account sealed? " + Account.class.isSealed());
for (Class<?> c : Account.class.getPermittedSubclasses()) {
String kind = java.lang.reflect.Modifier.isFinal(c.getModifiers()) ? "final"
: c.isSealed() ? "sealed" : "non-sealed";
System.out.println(" permits " + c.getSimpleName() + " (" + kind + ")");
}
System.out.println("HomeLoan is an Account: " + (new HomeLoan() instanceof Account));
}
}
Account sealed? true permits Savings (final) permits Current (sealed) permits Loan (non-sealed) HomeLoan is an Account: true
Class.isSealed() and getPermittedSubclasses() were added for reflection. Loan is non-sealed, so HomeLoan can extend it freely.
Example 3: Extending without permission
public class NotPermitted {
sealed interface Shape permits Circle { }
record Circle(double r) implements Shape { }
// Square is not listed in "permits"
record Square(double side) implements Shape { }
public static void main(String[] args) {
System.out.println(new Square(2));
}
}
NotPermitted.java:6: error: class is not allowed to extend sealed class: Shape (as it is not listed in its 'permits' clause)
record Square(double side) implements Shape { }
^
1 error
4. How the Hierarchy Is Restricted
5. Important Points and Best Practices
- Combine sealed interfaces with records to model data with a fixed set of shapes.
- Use
non-sealedonly when you deliberately want an extension point. - Sealing does not affect access modifiers; a sealed class can still be
public. - Adding a new permitted subtype is a breaking change for code that handles all cases, which is usually what you want: the compiler shows every place to update.
6. Summary
- Sealed classes and interfaces became standard in Java 17 (JEP 409).
- The
permitsclause lists the only allowed direct subtypes. - Each subtype must be
final,sealedornon-sealed. - Sealed types work hand in hand with records and pattern matching.
Related Tutorials
7. References
Frequently Asked Questions (FAQ)
Q1. What is a sealed class in Java?
A class or interface that restricts which classes may extend or implement it, using the permits clause. It became standard in Java 17.
Q2. What modifiers can a permitted subclass have?
It must be final, sealed (with its own permits) or non-sealed.
Q3. What does non-sealed mean?
It reopens that branch of the hierarchy, so any class may extend the non-sealed subclass.
Q4. Can a record implement a sealed interface?
Yes. Records are implicitly final, so they are valid permitted subtypes, and this combination is very common.