Introduction
Java 17, released in September 2021, finalised sealed classes as a standard language feature under JEP 409. Sealed classes had been introduced as a preview in Java 15 (JEP 360) and refined in Java 16 (JEP 397). The Java 17 release marked them as stable: the syntax and semantics were fixed, and the feature would receive no further breaking changes. The stable release of java 17 sealed classes stable means the feature can be used in production code without the --enable-preview flag, with the full support of the long-term-support release cycle that Java 17 enjoys.
For a Java learner, java 17 sealed classes stable is the foundation for the modern Java type-system stack: sealed classes pair with records (finalised in Java 16), pattern matching for instanceof (finalised in Java 16), record patterns (finalised in Java 21), and pattern matching for switch (finalised in Java 21). This post walks through the permits syntax, the rules for permitted subclasses in Java 17, the integration with modules, and the exhaustive switch check that the compiler provides.
What is Java 17 Sealed Classes Stable?
A sealed class in Java 17 is declared with the modifiers sealed and permits. The sealed modifier tells the compiler that the class is open only to a specific list of subclasses; the permits clause lists those subclasses by simple name (when in the same source file) or by fully qualified name (when in a different file). For example, public sealed class Shape permits com.example.Circle, com.example.Square, com.example.Triangle {} declares that Shape can be extended only by Circle, Square, and Triangle, which may live in different files or even different packages of the same module.
Conceptually, the Java 17 stable form is identical to the Java 15 preview form for the surface syntax. The differences are operational: the feature no longer requires --enable-preview to compile, the bytecode emitted is tagged as a PermittedSubclasses attribute that all conformant Java 17 JVMs understand, and the feature interacts cleanly with the Java module system via the java.lang.classfile API. The Java 17 release is the first long-term-support release with sealed classes, which means production deployments can rely on the feature for years.
How Java 17 Sealed Classes Stable Works - Step by Step
Step 1: Declare the sealed class with the permits clause. The permits clause lists every permitted subclass by name. In Java 17, permitted subclasses can live in different files of the same package, or in different packages of the same module, without any extra annotation.
Step 2: Declare each permitted subclass with one of three modifiers: final, sealed (with its own permits), or non-sealed. The compiler rejects any permitted subclass that lacks one of these modifiers. The non-sealed modifier opens the closure below this subclass: any class can extend it, but the subclass itself is still a permitted direct subclass of the sealed parent.
Step 3: The compiler writes a PermittedSubclasses attribute into the .class file of the sealed class. This attribute lists the fully qualified names of all permitted subclasses. At runtime, the JVM reads this attribute when answering the question "is class X a sealed class?" via Class.isSealed() and "what classes are permitted?" via Class.permittedSubclasses().
Step 4: Use the sealed class as a base type. Variables of type Shape can hold any instance of the permitted subclasses. The compiler knows at compile time that no other subclass of Shape exists, so a switch expression with one arm per permitted subclass is exhaustive without a default arm.
Step 5: Reflection reveals the permits. The methods Class.isSealed(), Class.permittedSubclasses(), and the related ClassRecordComponent[] array on records give reflective access to the sealed hierarchy at runtime. This is a stable API in Java 17, used by serialisation frameworks, mocking libraries, and code generators.
Java Program for Sealed Classes Stable
import java.util.List;
public class SealedStableDemo {
// (1) Sealed interface with three record subclasses
public sealed interface PaymentMethod
permits CreditCard, DebitCard, Cash, Voucher {}
public record CreditCard(String number, String holder) implements PaymentMethod {}
public record DebitCard(String number, String holder) implements PaymentMethod {}
public record Cash(int cents) implements PaymentMethod {}
public record Voucher(String code, int cents) implements PaymentMethod {}
// (2) Sealed class with nested sealed hierarchy
public sealed abstract class Account
permits SavingsAccount, CheckingAccount {}
public final class SavingsAccount extends Account {
private final long balanceCents;
public SavingsAccount(long b) { this.balanceCents = b; }
public long balanceCents() { return balanceCents; }
}
public final class CheckingAccount extends Account {
private final long balanceCents;
private final long overdraftCents;
public CheckingAccount(long b, long o) {
this.balanceCents = b; this.overdraftCents = o;
}
public long balanceCents() { return balanceCents; }
public long overdraftCents() { return overdraftCents; }
}
// (3) Exhaustive switch with no default arm
static String describe(PaymentMethod pm) {
return switch (pm) {
case CreditCard cc -> "Credit card ****"
+ cc.number().substring(cc.number().length() - 4)
+ " (" + cc.holder() + ")";
case DebitCard dc -> "Debit card ****"
+ dc.number().substring(dc.number().length() - 4)
+ " (" + dc.holder() + ")";
case Cash c -> "Cash " + format(cents(c.cents()));
case Voucher v -> "Voucher " + v.code()
+ " worth " + format(cents(v.cents()));
};
}
// (4) Exhaustive switch over Account
static String describe(Account a) {
return switch (a) {
case SavingsAccount s -> "Savings: " + format(s.balanceCents());
case CheckingAccount c -> "Checking: " + format(c.balanceCents())
+ " (overdraft " + format(c.overdraftCents()) + ")";
};
}
// Helper: compute the cents value for an int (no-op for clarity)
static long cents(int c) { return c; }
// Helper: format cents as dollars
static String format(long c) {
return String.format("$%d.%02d", c / 100, c % 100);
}
public static void main(String[] args) {
// (3) Exhaustive switch on PaymentMethod
List<PaymentMethod> methods = List.of(
new CreditCard("4111111111111234", "Alice"),
new DebitCard("5555555555555567", "Bob"),
new Cash(1550),
new Voucher("WELCOME10", 1000));
for (PaymentMethod m : methods) {
System.out.println("(3) " + describe(m));
}
// (4) Exhaustive switch on Account
SealedStableDemo outer = new SealedStableDemo();
Account s = outer.new SavingsAccount(50000);
Account c = outer.new CheckingAccount(12000, 5000);
System.out.println("(4) " + describe(s));
System.out.println("(4) " + describe(c));
// (5) Reflection on sealed
System.out.println("(5) PaymentMethod.isSealed(): "
+ PaymentMethod.class.isSealed());
Class<?>[] subs = PaymentMethod.class.permittedSubclasses();
System.out.println("(5) permitted subclasses:");
if (subs != null) {
for (Class<?> sub : subs) {
System.out.println(" " + sub.getSimpleName());
}
}
// (6) Reflection on Account
System.out.println("(6) Account.isSealed(): "
+ Account.class.isSealed());
Class<?>[] accSubs = Account.class.permittedSubclasses();
System.out.println("(6) permitted subclasses:");
if (accSubs != null) {
for (Class<?> sub : accSubs) {
System.out.println(" " + sub.getSimpleName());
}
}
// (7) Non-sealed demonstration (skipping for brevity in this demo)
System.out.println("(7) Cash.class.isSealed(): "
+ Cash.class.isSealed());
}
}
Code Explanation - Line by Line
Section (1) declares a sealed interface PaymentMethod with four permitted record subclasses: CreditCard, DebitCard, Cash, and Voucher. The permits clause lists them in the same source file by simple name, which Java 17 allows for permitted subclasses in the same compilation unit. Because all four subclasses are records, they are implicitly final, so the closure of PaymentMethod is exactly these four types.
Section (2) declares a sealed abstract class Account with two final subclasses SavingsAccount and CheckingAccount. The abstract modifier on Account is allowed because sealed classes can be abstract; they cannot be instantiated directly. Each subclass is declared final, which means it cannot be extended further and the closure of Account is exactly these two classes.
Method (3) describe is the canonical exhaustive switch expression over the sealed PaymentMethod hierarchy. The switch has one arm per permitted subclass and no default case. The compiler verifies exhaustiveness at compile time because PaymentMethod is sealed with exactly four permitted subclasses, all final. If you later added a Crypto payment method to the permits list without updating describe, the compiler would emit an error.
Method (4) describe over Account is the same pattern with an abstract sealed class instead of a sealed interface. The switch arms destructure SavingsAccount and CheckingAccount; the compiler verifies exhaustiveness against the two final permitted subclasses. The describe method reads the balanceCents() and overdraftCents() accessor methods directly because Account is a regular abstract class (not a record) and its subclasses are regular final classes (also not records).
Section (5) is the reflective introspection of PaymentMethod. The Class.isSealed() method returns true for a sealed class, and Class.permittedSubclasses() returns an array of Class objects for the permitted subclasses. The output lists CreditCard, DebitCard, Cash, and Voucher in the order they appear in the permits clause. This reflective access is stable in Java 17 and is used by serialisation frameworks to verify that a deserialised value is one of the permitted subclasses.
Section (6) is the reflective introspection of Account. The Class.isSealed() method returns true even though Account is an abstract class, not an interface. The permitted subclasses SavingsAccount and CheckingAccount are listed in the order they appear in the permits clause.
Section (7) demonstrates that the Cash record itself is not sealed. Records are implicitly final, so isSealed() returns false and permittedSubclasses() returns null. This is consistent: a record cannot have subclasses, so the question "what subclasses are permitted?" has no answer.
Sample Input and Output
Input: args = [] (uses fixed demo data)
Output:
(3) Credit card ****1234 (Alice)
(3) Debit card ****5567 (Bob)
(3) Cash $15.50
(3) Voucher WELCOME10 worth $10.00
(4) Savings: $500.00
(4) Checking: $120.00 (overdraft $50.00)
(5) PaymentMethod.isSealed(): true
(5) permitted subclasses:
CreditCard
DebitCard
Cash
Voucher
(6) Account.isSealed(): true
(6) permitted subclasses:
SavingsAccount
CheckingAccount
(7) Cash.class.isSealed(): false
The output confirms that the exhaustive switch expression dispatches correctly over the four PaymentMethod subclasses and the two Account subclasses, that the Class.isSealed() reflective method returns true for both the sealed interface PaymentMethod and the sealed abstract class Account, and that permittedSubclasses() returns the four PaymentMethod records in the order declared in the permits clause. The Cash record, being implicitly final, returns false for isSealed() because final classes are not sealed in the language's terminology.
Common Mistakes to Avoid
The first mistake is using --enable-preview when compiling sealed classes in Java 17 or later. The preview flag was required in Java 15 and 16, but it is unnecessary and produces a warning in Java 17. Production code should not pass --enable-preview for sealed-class compilation in Java 17+.
The second mistake is omitting the permits clause on a sealed class that has permitted subclasses in different files. The compiler can infer the permits list only when all permitted subclasses are in the same source file as the sealed class. For permitted subclasses in different files, the permits clause must list them explicitly by fully qualified name.
The third mistake is declaring a permitted subclass in a different module. In Java 17, permitted subclasses must be in the same module as the sealed class. The compiler rejects cross-module permitted subclasses with "permitted subclass in different module". If you need cross-module sealing, you must refactor your module structure.
The fourth mistake is assuming that adding a new subclass to the permits clause is backwards compatible at runtime. The .class file of the sealed class includes the PermittedSubclasses attribute listing all permitted subclasses; changing this list is a binary-incompatible change for any code that uses the sealed class. Use semantic-versioning minor or major bumps when changing the permits clause.
Real-World Applications
In production Java code, sealed classes are heavily used in domain modelling, event sourcing, and result-type modelling. Spring Framework's ApplicationEvent hierarchy in Spring Boot 3.x uses sealed classes for the closed set of event subtypes. The Jackson JSON library's JsonNode hierarchy in version 3.x uses sealed classes for ObjectNode, ArrayNode, and TextNode. The Reactor project's Flux and Mono hierarchies use sealed classes for the closed set of operator subtypes.
In build tooling, the Gradle build tool's task-result type is a sealed hierarchy of Success, Failure, and UpToDate in Gradle 8.x. The Maven build tool's lifecycle phase is a sealed enum-like class. Both rely on the exhaustive switch check to ensure that adding a new result type forces updates everywhere the type is switched over.
In compiler and parser code, the JavaParser library uses sealed classes for the AST node hierarchy, which lets visitors use exhaustive switch expressions. The Eclipse JDT compiler uses sealed classes for the type-binding hierarchy, which lets type-resolution code use exhaustive pattern matching. The IntelliJ IDEA PSI tree uses sealed-class-like patterns for the closed set of PSI element subtypes.
Conclusion
Java 17 sealed classes stable is the production-ready form of the third inheritance-control option: open only to a closed set of permitted subclasses. Combined with records, pattern matching for instanceof, record patterns, and pattern matching for switch, sealed classes give Java a fully modern type-system stack for modelling algebraic data types with exhaustive compile-time dispatch. Next, study Java 21 virtual threads for high-throughput concurrency, which is the marquee feature of the Java 21 LTS release.
Comments
Comments
Post a Comment