Java Sealed Classes and Interfaces: sealed, permits, final and non-sealed (OCP 21)
Sealed classes and interfaces for the OCP 21 exam: sealed and permits, the final, sealed or non-sealed rule for direct subclasses, same package or module, when permits can be omitted, nested subclasses, sealed interfaces, and exhaustive pattern-matching switches.
kvi5hnuCode Sprout team member7 min readOn this page
A normal class is open: anyone can extend it. A final class is closed: nobody can. Sealed types (standard since Java 17) sit between the two. A sealed class or interface lists exactly which types may directly extend or implement it.
That gives you something an enum gives for values: a closed set of known subtypes. The compiler can use this knowledge, most importantly to check that a pattern-matching switch covers every case without a default.
Declaring a sealed class
public abstract sealed class Payment permits Card, Cash, Voucher { }
public final class Card extends Payment { }
public final class Cash extends Payment { }
public non-sealed class Voucher extends Payment { }
There are three keywords to know:
sealedmarks the class or interface as restricted.permitslists the allowed direct subtypes.non-sealedmarks a subtype that reopens its branch to any class. It's the only hyphenated keyword in Java, and it's contextual:non-sealedstill works as an expression meaningnonminussealed.
sealed is a modifier, so it goes before class. public class sealed Frog fails, because sealed is a restricted identifier that can't be used as a type name. Sealed classes are often also abstract, but they don't have to be. sealed final is an illegal combination.
The rules for direct subclasses
1. Every permitted subclass must actually extend the sealed class. A class that's listed but doesn't extend it gives "invalid permits clause (class Q must extend sealed class)".
2. Only listed classes may extend it.
public abstract sealed class Shape permits Circle { }
public final class Circle extends Shape { }
public final class Star extends Shape { } // DOES NOT COMPILE:
// class is not allowed to extend sealed class: Shape (as it is not listed in its 'permits' clause)
3. Every direct subclass must declare exactly one of final, sealed or non-sealed. Sealed classes have no implicit modifiers here, and forgetting one gives "sealed, non-sealed or final modifiers expected".

| Subclass modifier | Meaning | Its own subclasses |
|---|---|---|
final | the branch ends here | none |
sealed (+ its own permits) | the branch continues with a fixed list | only those listed |
non-sealed | the branch is reopened | any class |
public sealed class Plan permits Membership { }
public sealed class Membership extends Plan permits LoyaltyCard { }
public final class LoyaltyCard extends Membership { } // indirect subclass of Plan: fine
Plan doesn't name LoyaltyCard. Only direct subclasses go in permits. The full hierarchy is still known at compile time.
A non-sealed subclass doesn't break the seal of its parent. Every class Web extends Online is still an Online, and Online is in the parent's list. The author of the sealed class chose to allow that open branch.
4. Location. In code without named modules (the unnamed module), a sealed class and its direct subclasses must be in the same package. Otherwise javac reports "class Payment in unnamed module cannot extend a sealed class in a different package" (oddly, the message names the sealed class, not the subclass). Inside a named module (chapter 12), different packages of the same module are allowed.
5. No anonymous or local subclasses. new Payment() { } and a local class extending Payment fail ("anonymous classes must not extend sealed classes"), because they could never be listed in permits.
When permits can be omitted
| Where the direct subclasses are | permits clause |
|---|---|
| in a different file | required |
| in the same file as the sealed class | optional |
| nested inside the sealed class | optional |
If you leave out permits, the compiler uses the subclasses it finds in the same file. With no subclasses there at all, you get "sealed class must have subclasses". That's also what happens if the subclasses live in other files, and each of them then reports "is not allowed to extend sealed class".
When you do list nested subclasses, use their qualified names:
public sealed class Ticket permits Child { // DOES NOT COMPILE: cannot find symbol Child
final class Child extends Ticket { }
}
public sealed class Ticket permits Ticket.Child { // compiles
final class Child extends Ticket { }
}
For nested subclasses, the simplest choice is to leave out permits entirely.
Sealed interfaces
Interfaces can be sealed too. Their permits list can include classes that implement the interface and interfaces that extend it:
public sealed interface Channel permits Store, Online, Kiosk { }
public final class Store implements Channel { }
public non-sealed interface Online extends Channel { } // interfaces: sealed or non-sealed only
public record Kiosk(String id) implements Channel { } // records are implicitly final
A sub-interface can't be final, because interfaces never can be. So it must be sealed or non-sealed. Records (article 41) are implicitly final, and enums are implicitly final or sealed, so both can be permitted subtypes without writing any modifier. Sealed interfaces with record implementations are the classic modern way to model "one of these shapes of data".
Sealed types and switch
With pattern matching for switch (article 13), a switch over a sealed type is exhaustive when it covers every permitted subtype, so no default is needed:
abstract sealed class Transfer permits Wire, Cash { }
final class Wire extends Transfer { }
final class Cash extends Transfer { }
static String name(Transfer f) {
return switch (f) {
case Wire t -> "wire";
case Cash b -> "cash";
};
}
Exhaustiveness depends on the details:
- If
Transferisn't abstract, a plainTransferobject is also possible. The switch then needscase Transfer x, ordefault, or it fails with "the switch expression does not cover all possible input values". - A
non-sealedsubtype is covered by a case for that type, which matches all of its unknown subclasses. - If a new permitted subclass is added later, every switch that's missing it stops compiling. That's the main benefit over a
defaultbranch, which would hide the new case.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
- Sealed classes have been final since Java 17 (JEP 409). Java 21 made them pay off with exhaustive pattern
switch(article 13).
Exam traps from this article
A complete example
The program models payments as an abstract sealed class with final, sealed and nested subclasses, plus a sealed interface with a non-sealed branch. It switches over both without any default.
import java.util.Arrays;
import java.util.List;
public class Solution {
// Sealed hierarchy: nested subclasses, so permits could be omitted; written out for clarity
abstract static sealed class Payment permits Card, Cash, Voucher {
final int cents;
Payment(int cents) { this.cents = cents; }
}
static final class Card extends Payment { // final: closed here
final String last4;
Card(int cents, String last4) { super(cents); this.last4 = last4; }
}
static final class Cash extends Payment {
Cash(int cents) { super(cents); }
}
static sealed class Voucher extends Payment permits GiftVoucher { // sealed again
Voucher(int cents) { super(cents); }
}
static final class GiftVoucher extends Voucher {
final String from;
GiftVoucher(int cents, String from) { super(cents); this.from = from; }
}
// Sealed interface with a non-sealed branch that anyone may extend
sealed interface Channel permits Store, Online { }
static final class Store implements Channel { }
non-sealed interface Online extends Channel { }
static class MobileApp implements Online { } // allowed: Online is non-sealed
static String describe(Payment p) {
return switch (p) { // exhaustive: no default needed
case Card c -> "card ending " + c.last4;
case Cash c -> "cash";
case GiftVoucher g -> "gift voucher from " + g.from;
case Voucher v -> "voucher"; // after its subclass
};
}
static String where(Channel ch) {
return switch (ch) {
case Store s -> "in store";
case Online o -> "online (" + o.getClass().getSimpleName() + ")";
};
}
public static void main(String[] args) {
List<Payment> payments = List.of(
new Card(1250, "4821"), new Cash(300),
new Voucher(500), new GiftVoucher(2000, "Grandma"));
int total = 0;
for (Payment p : payments) {
System.out.println(p.cents + " cents by " + describe(p));
total += p.cents;
}
System.out.println("total " + total + " cents");
System.out.println(where(new Store()) + ", " + where(new MobileApp()));
System.out.println("Payment permits: " + Arrays.stream(Payment.class.getPermittedSubclasses())
.map(Class::getSimpleName).toList());
System.out.println("Payment sealed? " + Payment.class.isSealed()
+ ", Online sealed? " + Online.class.isSealed());
}
}
Output:
1250 cents by card ending 4821
300 cents by cash
500 cents by voucher
2000 cents by gift voucher from Grandma
total 4050 cents
in store, online (MobileApp)
Payment permits: [Card, Cash, Voucher]
Payment sealed? true, Online sealed? false
Points to notice:
Paymentpermits three direct subclasses, andVoucheris itself sealed with one more.GiftVoucherisn't listed inPayment, and it doesn't need to be.- In
describe,case GiftVouchercomes beforecase Voucher. The reverse order would be a dominance error, because the more general case would catch everything first. - The switch in
describeis exhaustive becausePaymentis abstract and every branch is covered. MobileAppimplementsOnlinewithout being named anywhere, becauseOnlineisnon-sealed.getPermittedSubclasses()andisSealed()expose the seal through reflection.
Common questions
When should I use sealed classes instead of an enum?
Use an enum when each alternative is a single fixed instance. Use a sealed hierarchy when the alternatives are different types that carry different data, such as a Card with a number versus Cash.
Does sealed stop subclasses from overriding methods?
No. It only restricts which types may extend or implement. Overriding rules stay the same.
Can a sealed class have a final method or a constructor?
Yes. It's a normal class in every other respect.
Summary
sealedwithpermitsrestricts the direct subtypes of a class or interface to a named list.- Each direct subclass must be
final,sealed(with its own list) ornon-sealed. Sub-interfaces can only besealedornon-sealed. - Permitted subtypes must extend the sealed type and live in the same package (or the same named module).
permitsmay be omitted when the subtypes are in the same file or nested. Nested names inpermitsmust be qualified.- A pattern switch covering every permitted subtype of an abstract sealed type needs no
default.
Practice quiz
Test yourself with the sealed classes quiz: 10 exam-style questions with explanations.
Previous: Java Enums: Values, Constructors, Fields, Methods and switch (OCP 21)
Next: Java Records: Compact Constructors, Accessors and Customization (OCP 21)
Related reading
- Java Primitive Types, Literals, Wrapper Classes and Text Blocks (OCP 21)
- Java Sealed Classes and Interfaces: Controlling Inheritance
- Java Interfaces: Declaring, Implementing and Inheriting Abstract Methods (OCP 21)
- Java Abstract Classes and Abstract Methods (OCP 21)
- Java Inheritance and Class Modifiers: extends, Object, this and super (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.