OOP Basics ·
‹ Previous Next ›
⏱ 5 min read Modified: 2026-11-28

Sealed Classes and Interfaces in Java

A sealed class in Java is a class or interface that lists exactly which classes may extend it. The list goes after the permits keyword, and any other class that tries to extends it fails to compile. Every permitted subclass must pick one of three modifiers: final, sealed or non-sealed. Sealed classes became a standard language feature in Java 17 (JEP 409) after two preview rounds in Java 15 and 16.

public sealed interface Shape permits Circle, Rect { }

public record Circle(double r) implements Shape { }
public record Rect(double w, double h) implements Shape { }

static double area(Shape s) {
    return switch (s) {                   // no default needed
        case Circle c -> Math.PI * c.r() * c.r();
        case Rect r   -> r.w() * r.h();
    };
}

System.out.println(area(new Rect(2, 3))); // 6.0

The real payoff shows up in switch: the compiler knows every implementation of Shape, so it checks that no case is missing and you do not need default. Add a third shape to permits, and every such switch stops compiling and points you at the branch you have to add. Below are the permits rules, the three subclass modifiers, sealed interfaces and the link to pattern matching, each with the exact javac message that OCP exam questions are built on.

Why sealed classes exist

Before Java 17 a class author had only two choices: let everyone extend the class, or nobody, with final. There was nothing in between. You could make the constructor package-private so that subclasses could only appear in the same package, but neither the compiler nor a reader of the code could see that restriction, and the trick does not work for interfaces at all.

A sealed class fills that gap. It models a domain where the set of variants is known up front and should not change:

  • a payment method: card, cash or bank transfer;
  • the result of an operation: success or failure;
  • a syntax tree node: number, sum, product;
  • a domain event: created, paid, cancelled.

Note that sealed restricts inheritance, not use. The class can be public, used from any package, instantiated and called; the only thing forbidden is declaring new subclasses outside the list. That is what separates sealed from access modifiers, which hide the class itself.

Syntax: sealed and permits

The sealed modifier goes before class or interface, and permits with the list of allowed subclasses comes after extends/implements. The order of the clauses is fixed: superclass and interfaces first, then permits.

public sealed abstract class Payment permits Card, Cash, Transfer { }

public final class Card extends Payment { }
public final class Cash extends Payment { }
public sealed abstract class Transfer extends Payment permits Sepa, Swift { }

public final class Sepa extends Transfer { }
public non-sealed class Swift extends Transfer { }

The link works both ways. The parent names its subclasses in permits, and each subclass must actually extend that parent. If a class is listed in permits but does not extends the parent, the compiler reports it on the parent:

sealed class A permits B { }
final class B { }               // forgot extends A

// error: invalid permits clause
//   (class B must extend sealed class)

The opposite case: a class extends a sealed parent but is not in its permits list:

sealed class A permits B { }
final class B extends A { }
final class C extends A { }     // C is not listed

// error: class is not allowed to extend sealed class: A
//   (as it is not listed in its 'permits' clause)

A sealed class with no subclasses at all does not compile either: sealed class A { } gives error: sealed class must have subclasses. If there really are no subclasses, you want final.

sealed and permits are contextual keywords: they only mean something in a class declaration, so old code with a variable named int permits still compiles. non-sealed, on the other hand, is the first hyphenated keyword in Java.

Subclasses: final, sealed or non-sealed

Every class in permits must state explicitly what happens to the hierarchy below it. There is no default; a plain class B extends A does not compile:

sealed class A permits B { }
class B extends A { }

// error: sealed, non-sealed or final modifiers expected
Subclass modifier Can it be extended further When to choose it
final No, the branch ends here A leaf variant: Card, Cash. The most common choice
sealed Only by the classes in its own permits The variant splits into known sub-variants: Transfer → Sepa, Swift
non-sealed Yes, by anyone, like a regular class An extension point for other people's code: plugins, user-defined types

non-sealed deliberately reopens a branch: Swift from the example above can be extended without restrictions, including from another package or module. The hierarchy stays closed as far as the compiler is concerned: it still knows that every Payment is a Card, a Cash or a Transfer, and every Transfer is a Sepa or a Swift (including all subclasses of Swift).

class FastSwift extends Swift { }    // compiles: Swift is non-sealed

non-sealed is only allowed on a direct subtype of a sealed type. On a class without a sealed parent it means nothing, and the compiler checks that:

class A { }
non-sealed class B extends A { }

// error: non-sealed modifier not allowed here
//   (class B does not have any sealed supertypes)

The modifiers are mutually exclusive: sealed final class gives error: illegal combination of modifiers: final and sealed. sealed and abstract, however, combine perfectly well; an abstract sealed parent is the most convenient option, for the reason explained in the switch section.

permits rules: package, module, direct subclass

Permitted subclasses cannot live just anywhere. The JLS sets three conditions:

  1. Direct subclass. permits lists direct subclasses only. Grandchildren go into the permits of the next level: Sepa is listed by Transfer, not by Payment.
  2. Accessibility. Every listed class must be accessible where the parent is declared.
  3. Same module or same package. In a named module (there is a module-info.java) the subclasses may sit in different packages of that module. Without a module, which is how most learning projects are set up, the parent and its subclasses must be in the same package.

The third rule is the one that bites in real projects:

// file a/Vehicle.java
package a;
public sealed class Vehicle permits b.Car { }

// file b/Car.java
package b;
public final class Car extends a.Vehicle { }

// error: class Vehicle in unnamed module cannot extend a sealed class in a different package

The restriction exists so that the hierarchy can be checked as a whole: the compiler and the JVM must see all subclasses together. A package in the unnamed module, or a named module, is the boundary inside which code is compiled and shipped as one unit.

When you can leave out permits

If all subclasses are declared in the same source file as the sealed type, permits can be omitted. The compiler builds the list itself from the classes in that file that extend the parent.

sealed interface Expr { }                 // no permits clause
record Num(int v) implements Expr { }
record Add(Expr l, Expr r) implements Expr { }

static int eval(Expr e) {
    return switch (e) {
        case Num n -> n.v();
        case Add(Expr l, Expr r) -> eval(l) + eval(r);
    };
}

System.out.println(eval(new Add(new Num(2), new Add(new Num(3), new Num(4)))));  // 9
System.out.println(Arrays.toString(Expr.class.getPermittedSubclasses()));        // [class Num, class Add]

This style is most common for small hierarchies of records or nested classes:

public sealed interface Result<T> {
    record Ok<T>(T value) implements Result<T> { }
    record Err<T>(String message) implements Result<T> { }
}

As soon as a subclass moves to its own file, permits becomes mandatory; otherwise you get class is not allowed to extend sealed class.

Sealed interfaces

An interface is sealed the same way as a class. Its permits list may contain both classes that implement it (implements) and interfaces that extend it (extends).

public sealed interface Shape permits Circle, Rect, Polygon { }

public record Circle(double r) implements Shape { }
public record Rect(double w, double h) implements Shape { }
public non-sealed interface Polygon extends Shape { }

public final class Triangle implements Polygon { }   // Polygon is open to everyone

A sub-interface has fewer options than a class: an interface cannot be final, so only sealed and non-sealed remain. The compiler puts it like this:

sealed interface A permits B { }
interface B extends A { }

// error: sealed or non-sealed modifiers expected

final interface B extends A { }
// error: illegal combination of modifiers: interface and final

A sealed interface is often handier than a sealed class: a class can implement several interfaces, and records and enums cannot extend classes at all. How interfaces differ from abstract classes in general is covered in Abstract Classes and Methods, and interfaces themselves in Interfaces in Java.

Records and enums in a sealed hierarchy

A record is implicitly final, so you can list it in permits without any extra modifier, as the Shape and Expr examples do. "Sealed interface + records" is the standard way to express an algebraic data type in Java: the interface fixes the set of variants, and each record holds the data of one variant.

An enum can be a permitted subtype of a sealed interface too, because a plain enum is implicitly final. An enum whose constants have bodies (PLUS { ... }) is made sealed by the compiler: its constants become permitted anonymous subclasses. You cannot write sealed enum yourself: error: modifier sealed not allowed here.

sealed interface Command permits Simple, Move { }
enum Simple implements Command { START, STOP }
record Move(int dx, int dy) implements Command { }

static String describe(Command c) {
    return switch (c) {
        case Simple.START -> "start";       // enum constants as case labels
        case Simple.STOP  -> "stop";
        case Move(int dx, int dy) -> "move by " + dx + "," + dy;
    };
}

This switch is exhaustive without default: the compiler knows every variant of Command and every constant of Simple. A record itself cannot be declared sealed, since records are always final. More on enums in Enums in Java.

Sealed types and pattern matching: switch without default

Sealed classes were designed together with pattern matching for switch (JEP 441, standard since Java 21). A switch with type patterns must be exhaustive, covering every possible value. For a regular class or interface the only way to get there is a default branch; for a sealed type it is enough to list all the subtypes.

static String fee(Payment p) {
    return switch (p) {
        case Card c  -> "1.5%";
        case Cash c  -> "0";
        case Sepa s  -> "0.20";
        case Swift s -> "15";    // covers Swift and all of its subclasses
    };
}

System.out.println(fee(new FastSwift()));   // 15

There is no Transfer branch here, and none is needed: Transfer is an abstract sealed class, and all its variants (Sepa and Swift) are listed. The non-sealed branch Swift is covered by a single case Swift, no matter how many subclasses it gets.

Forget a variant and the code does not compile, which is the whole point of sealed:

static double area(Shape s) {
    return switch (s) {
        case Circle c -> Math.PI * c.r() * c.r();
    };                                      // Rect and Polygon are missing
}

// error: the switch expression does not cover all possible input values

A switch statement (one that returns nothing) gets the same message with switch statement: exhaustiveness is required for any switch that uses patterns, not only for switch expressions. And if you add default "just in case", the compiler can no longer warn you when a new subtype appears, so leave default out for sealed types.

Trap: a non-abstract sealed parent

Declare sealed class Transfer without abstract, and the switch above gains a fourth variant: an instance of Transfer itself, created with new Transfer(). There is no branch for it, so the compiler reports the switch expression does not cover all possible input values even though every subclass is listed. Two fixes: make the intermediate sealed class abstract, or add case Transfer t.

Three more rules worth knowing about such a switch:

  • Guards with when do not count as full coverage. case Circle c when c.r() > 10 covers only big circles, so without an unguarded case Circle c the switch is not exhaustive again.
  • null is not part of the coverage. An exhaustive switch without case null throws NullPointerException on a null value, just like a regular switch.
  • Protection against separate compilation. If a new subtype appears after the switch was compiled and one of its objects gets there, the JVM throws MatchException, from an implicit default the compiler adds on its own.

Sealed interfaces usually go hand in hand with record patterns, which take a record apart right in the case: case Rect(double w, double h) -> w * h. They are covered in detail in Java Records, and the arrow syntax of switch expressions in Switch-Case Statement in Java.

Sealed types, casting and instanceof

A closed hierarchy helps the compiler beyond switch. It also rejects casts that can never succeed. Normally a cast from an interface type to a non-final class always compiles, because some subclass might implement the interface. With a sealed interface the compiler knows every implementor and can prove there is no overlap:

sealed interface Shape permits Circle { }
final class Circle implements Shape { }
class Square { }                         // a regular class, not final

void m(Square sq, Shape s) {
    Shape x = (Shape) sq;                // error: incompatible types: Square cannot be converted to Shape
    boolean b = s instanceof Square;     // error: incompatible types: Shape cannot be converted to Square
}

Remove sealed from Shape and the first line compiles (and fails with ClassCastException at run time), because a subclass of Square could implement a regular interface. Now that is impossible: Shape permits only Circle. The basics of reference casting and instanceof are in Upcasting and Downcasting in Java.

Restrictions: anonymous and local classes, lambdas

An anonymous or local class has no name that could go into permits, so it may not extend a sealed type, even one declared in the same file:

sealed interface A permits B { }
final class B implements A { }

A a = new A() { };                       // error: anonymous classes must not extend sealed classes

void m() {
    final class L implements A { }       // error: local classes must not extend sealed classes
}

A lambda is essentially an anonymous implementation too, so a sealed interface cannot be its target type, even with exactly one abstract method:

sealed interface Task permits Job { void run(); }
final class Job implements Task { public void run() { } }

Task t = () -> { };   // error: incompatible types: Task is not a functional interface

Nested classes (static and inner), on the other hand, are allowed: they have a name, such as Result.Ok. The kinds of nested classes are compared in Inner and Nested Classes.

Sealed classes in reflection and in the JDK

Java 17 added two methods to java.lang.Class: isSealed() and getPermittedSubclasses(). The second returns an array of the permitted subtypes, or null if the type is not sealed.

System.out.println(Shape.class.isSealed());   // true
System.out.println(Arrays.toString(Shape.class.getPermittedSubclasses()));
// [class Circle, class Rect, interface Polygon]
System.out.println(Swift.class.getPermittedSubclasses());   // null, Swift is non-sealed

The JDK uses sealed types as well. For example, java.lang.constant.ConstantDesc (a description of a bytecode constant) permits exactly nine implementations:

System.out.println(Arrays.toString(ConstantDesc.class.getPermittedSubclasses()));
// [interface java.lang.constant.ClassDesc, interface java.lang.constant.MethodHandleDesc,
//  interface java.lang.constant.MethodTypeDesc, class java.lang.Double,
//  class java.lang.constant.DynamicConstantDesc, class java.lang.Float,
//  class java.lang.Integer, class java.lang.Long, class java.lang.String]

In bytecode the list is stored in the PermittedSubclasses attribute of the class file, and the JVM checks it when classes are loaded. So you cannot get around sealed by compiling a "forbidden" subclass separately: the class fails to load with IncompatibleClassChangeError.

final, sealed, abstract or a regular class: which to choose

The modifiers answer different questions: abstract says whether you can create an object of the class, while final/sealed say who may extend it. That is why sealed abstract is a normal combination and sealed final is not.

Declaration Who can extend it Exhaustive switch without default Typical use
class Any class No Regular classes, extension points
abstract class Any class No Shared implementation for an unknown set of subclasses
final class Nobody Yes (a single variant) Immutable values: String, Integer, records
sealed class or interface Only the classes in permits Yes A fixed set of variants: payments, events, results, ASTs
non-sealed subclass Any class Covered by one branch An open branch inside a closed hierarchy

Rule of thumb: if you are writing if (x instanceof A) ... else if (x instanceof B) ... or a type switch and you know there will be no more variants, make the root type sealed. If you expect other developers to keep adding variants, you want an ordinary hierarchy with polymorphic methods instead: adding a new class is easier than editing every switch. General inheritance principles are in Java Inheritance.

Does it compile? Sealed classes in OCP questions

The Oracle OCP exam tests sealed classes with short snippets: you have to say whether the code compiles. Every case below was checked on JDK 25; unless stated otherwise, the classes live in one file.

Code Result Why
sealed class A permits B { }
class B extends A { }
Does not compile The subclass needs final, sealed or non-sealed
sealed class A { }
final class B extends A { }
Compiles permits is inferred from the classes in the same file
sealed class A { } Does not compile A sealed class must have at least one subclass
sealed class A permits B { }
final class B { }
Does not compile A class in permits must extend A
sealed interface I permits J { }
final interface J extends I { }
Does not compile An interface cannot be final, only sealed or non-sealed
sealed interface I permits R { }
record R() implements I { }
Compiles A record is implicitly final
class A { }
non-sealed class B extends A { }
Does not compile non-sealed only on a subtype of a sealed type
sealed abstract class A permits B { }
final class B extends A { }
Compiles sealed and abstract are compatible
sealed interface I permits C { }
I i = new I() { };
Does not compile An anonymous class cannot extend a sealed type
Parent in package a, subclass in package b, no module-info.java Does not compile The unnamed module allows a single package only
sealed class T permits S { } (not abstract) + a switch with only case S s Does not compile T itself is not covered: it can be instantiated

Frequently asked questions

Which Java version introduced sealed classes?

Sealed classes and interfaces have been a standard feature since Java 17 (JEP 409). In Java 15 and 16 they were a preview feature that needed --enable-preview; compiling with --release 16 without it, javac reports sealed classes are not supported in -source 16. Exhaustive switch with type patterns became standard in Java 21.

What is the difference between sealed and final?

final forbids inheritance completely; sealed allows it only for the classes in the permits list. A final class is a hierarchy with one variant, a sealed one has several variants known up front. You cannot use both modifiers at once: illegal combination of modifiers: final and sealed.

Why does non-sealed exist if it reopens inheritance?

To close the hierarchy at the top while keeping one branch extensible. The compiler still knows every variant of the root: any subclass of a non-sealed class counts as part of that branch, so a switch stays exhaustive with a single case for it. Libraries use this to fix the core variants while letting users add their own under a dedicated branch.

Can a sealed interface be functional and used with a lambda?

No. A lambda creates an unnamed implementation that cannot be listed in permits, so a sealed interface is not considered functional even with a single abstract method. Assigning a lambda gives Task is not a functional interface, and @FunctionalInterface on a sealed interface does not compile either: Unexpected @FunctionalInterface annotation.

Practice

Reinforce this lesson with hands-on tasks, each with a level and a time estimate.

All module tasks →

Comments

Please log in or register to have a possibility to add comment.