Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java Sealed Class Inheritance: Syntax and Rules

Learn how Java sealed class inheritance restricts direct subtypes, which modifiers permitted subtypes need, and how sealed hierarchies support exhaustive pattern matching.

~6 min readJava
#sealed classes#Java 17#type hierarchy#pattern matching
Diagram of a sealed class hierarchy with permitted subtypes and a lock icon representing restricted inheritance.

Java sealed class inheritance restricts the direct subtypes of a class or interface. Introduced as a final feature in Java 17, sealed classes give you explicit control over the direct subtype hierarchy, which is useful for writing exhaustive pattern matching and for modeling domain states that should not be extended arbitrarily. This article covers the syntax, rules, and practical implications of sealed class inheritance.

Declaring a Sealed Class and Its Permitted Subtypes

A sealed class is declared with the sealed modifier. When direct subtypes are declared in separate source files, a permits clause lists every direct subtype allowed to extend the class. If the permitted subtypes are declared in the same compilation unit, the permits clause may be omitted. For example:

java
public sealed class Shape permits Circle, Rectangle, Triangle { // common fields and methods }

Each permitted subtype must be declared in the same module as the sealed class, or in the same package if the code is in the unnamed module. The compiler enforces this rule for source code, and the JVM enforces the corresponding class-file restriction for compiled classes; no other class can extend Shape unless it is one of the permitted subtypes.

Every permitted class must satisfy one of three conditions: be final, be sealed, or be non-sealed. A final class ends the hierarchy for that branch. A sealed class continues to restrict its own subtypes. A non-sealed class reopens the hierarchy, allowing arbitrary subclasses. A record is automatically final, so it satisfies the requirement without writing the modifier. If a sealed interface permits another interface as a subtype, that interface must be sealed or non-sealed.

java
public final class Circle extends Shape { } public sealed class Rectangle extends Shape permits Square { } public final class Square extends Rectangle { } public non-sealed class Triangle extends Shape { }

In this example, Circle cannot be extended further. Rectangle permits only Square. Triangle can be extended by any class, because non-sealed removes the restriction for that branch.

Rules That Govern Sealed Class Inheritance

Sealed class inheritance follows a few strict rules that you must understand to avoid compilation errors.

First, if you use a permits clause, it must list every direct subtype. You cannot have a subclass that is not listed, and you cannot list a class that does not directly extend the sealed class. If a subclass is in a different package but the same named module, it must still be listed explicitly.

Second, each permitted subtype must be in the same module as the sealed class. In a non-modular project, all classes are in the unnamed module, so permitted subtypes must be in the same package. This prevents the common mistake of trying to extend a sealed class from a different package without a module declaration.

Third, permitted subtypes do not all have to be nested in one file. Separate classes can be valid permitted subtypes as long as they are declared in the same module and the compiler can resolve the hierarchy. When permitted subtypes are declared in the same compilation unit, the permits clause is optional.

Fourth, a permitted subtype cannot be a primitive type, an array, or a generic type instantiation. It must be a named class or interface; records are acceptable because they are named final classes.

Finally, a sealed class may be abstract or non-abstract. An abstract sealed class cannot be instantiated directly. A non-abstract sealed class with a usable constructor can be instantiated, but that is unusual because the point of sealing is to control the hierarchy.

Why Sealed Classes Enable Exhaustive Pattern Matching

One of the main motivations for sealed class inheritance is exhaustive pattern matching in switch expressions and statements. Pattern matching for switch was previewed in Java 17 and became standard in Java 21, so on Java 17 the examples below need the preview flag. With pattern matching, the compiler can verify that the cases cover every permitted subtype of a sealed type. If they do, you do not need a default branch.

Consider this sealed hierarchy:

java
public sealed interface Expression permits Constant, Add, Multiply { int evaluate(); } public record Constant(int value) implements Expression { public int evaluate() { return value; } } public record Add(Expression left, Expression right) implements Expression { public int evaluate() { return left.evaluate() + right.evaluate(); } } public record Multiply(Expression left, Expression right) implements Expression { public int evaluate() { return left.evaluate() * right.evaluate(); } }

You can write a switch expression that handles every subtype:

java
public static int evaluate(Expression expr) { return switch (expr) { case Constant c -> c.value(); case Add a -> evaluate(a.left()) + evaluate(a.right()); case Multiply m -> evaluate(m.left()) * evaluate(m.right()); }; }

Because Expression is sealed and its permitted subtypes are all final records, the compiler knows that Constant, Add, and Multiply are the only possible subtypes. If you later add a new permitted subtype and forget to update the switch, the code will not compile. This is a significant advantage over traditional polymorphic dispatch, where missing a case is only caught at runtime.

Sealed Interfaces and Records as Permitted Subtypes

Sealed interfaces work the same way as sealed classes, except the permitted subtypes implement the interface instead of extending a class. They allow you to restrict implementations of an interface, which is useful for defining closed sets of behavior.

java
public sealed interface PaymentMethod permits CreditCard, PayPal, BankTransfer { void process(); }

Records are natural fits for sealed hierarchies because they are implicitly final. A record cannot be extended, so it satisfies the final requirement for a permitted subtype without any extra modifier.

java
public record CreditCard(String number, String expiry) implements PaymentMethod { public void process() { /* ... */ } }

Using records with sealed interfaces gives you immutable data carriers that are easy to pattern-match. This combination is particularly effective in domain modeling, where you want to represent a fixed set of alternatives without writing boilerplate equals, hashCode, and toString methods.

Common Mistakes When Working with Sealed Inheritance

One frequent mistake is forgetting to mark a permitted subtype as final, sealed, or non-sealed. The compiler will reject the class with an error such as class is not allowed to extend sealed class or permitted class must be final, sealed, or non-sealed. Always check that every permitted subtype has one of these modifiers.

Another mistake is trying to extend a sealed class from a different package without a module declaration. In a non-modular project, all classes are in the same unnamed module, but they must be in the same package. If you need to spread subtypes across packages, you must place the sealed class and its subtypes in a named module. In a named module, permitted subtypes may be in different packages inside that module.

A third issue is omitting a subtype from the permits list. If you have a class that extends the sealed class but is not listed, compilation fails. Conversely, listing a class that does not directly extend the sealed class also fails. The compiler is strict about the exact set of direct subtypes.

Finally, developers sometimes try to use a sealed class as a type for a variable and then expect to add new subtypes later without modifying the sealed class. That defeats the purpose. Sealed hierarchies are meant to be closed; if you anticipate external extension, use a different design.

Sealed Classes in Modular Codebases and Production Considerations

Sealed classes interact with the Java module system. All permitted subtypes must be in the same module as the sealed class. Therefore, a library cannot define a sealed class and then allow clients to add their own subtypes. That restriction is intentional: it keeps the hierarchy closed for security and maintainability.

From a production standpoint, sealed classes reduce the surface area for bugs. By restricting inheritance, you prevent unintended subclasses that might violate invariants. For example, a financial domain can model transaction types as a sealed class, ensuring that no external code can introduce a new transaction type that bypasses validation logic.

Migration from an abstract class to a sealed class requires careful planning. If you have an existing abstract class with many subclasses, you must list all of them in the permits clause and mark each as final, sealed, or non-sealed. This can be a large change, but it forces you to document the intended hierarchy explicitly. For direct subtypes that you want to leave open to further extension, mark them non-sealed; that weakens the sealed guarantee but can make migration easier.

Another production consideration is serialization. Sealed classes and records are subject to the same serialization rules as other classes. If serialized data can include instances from a sealed hierarchy, those concrete classes must be serializable, and compatibility must be managed across versions. Changing the permitted set can affect deserialization if old data refers to a subtype no longer in the permits list.

Performance is rarely a concern with sealed classes. The compiler emits ordinary bytecode with an additional class-file attribute that records the permitted subtypes; the sealing rules do not add per-call runtime overhead. The main cost is the added design discipline, which usually pays off in fewer bugs and clearer code.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.