Skip to lesson

Sealed classes and permits

A sealed class lists exactly which classes may extend it. sealed class Account permits Savings, Current means those two, and no others, can ever be its children. The compiler enforces the list, so the hierarchy is closed. Sealed classes became a standard feature in Java 17.

Why close a hierarchy: only known subtypes allowed

A sealed class or interface lists exactly which classes may extend or implement it, using permits, so the compiler knows every possible subtype.

So far a class had two settings. A normal or abstract class is open: any class, anywhere, may extend it. A final class is shut: nobody may extend it. Many real models sit in between. A bank offers exactly savings and current accounts.

Example 1 · The problem: an open hierarchy surprises old code

OpenHierarchyDemo.javaJava
import java.util.List;
abstract class Payment {    final int amount;
    Payment(int amount) {        this.amount = amount;    }}
class Upi extends Payment {    Upi(int amount) {        super(amount);    }}
class Card extends Payment {    Card(int amount) {        super(amount);    }}
// added months later by another teamclass GiftVoucher extends Payment {    GiftVoucher(int amount) {        super(amount);    }}
public class OpenHierarchyDemo {    static int fee(Payment p) {        if (p instanceof Upi) {            return 0;        } else if (p instanceof Card) {            return p.amount * 2 / 100;        }        throw new IllegalStateException("unknown payment: " + p.getClass().getSimpleName());    }
    public static void main(String[] args) {        List<Payment> payments = List.of(new Upi(500), new Card(1000), new GiftVoucher(300));        for (Payment p : payments) {            try {                System.out.println(p.getClass().getSimpleName() + " fee: " + fee(p));            } catch (IllegalStateException e) {                System.out.println("Crash at run time: " + e.getMessage());            }        }    }}
Output
Upi fee: 0
Card fee: 20
Crash at run time: unknown payment: GiftVoucher

What this code does

  • Payment is open, so another team could add GiftVoucher without touching fee. Nothing warned them that fee knows only two kinds.
  • The mistake shows up only at run time, on a real payment. A sealed parent turns "which kinds exist" into something the compiler checks.

A train ticket is exactly sleeper, AC 3-tier or AC 2-tier. The business decides the list, not whoever writes the next subclass.

With an open parent, code that handles "every kind" can never be sure. A method with if (a instanceof Savings) ... else if (a instanceof Current) ... needs a final else for kinds it has never heard of, and a new subclass added later falls into that else at run time. A sealed parent makes the list part of the type. Readers see every possible subtype in one line, and the compiler rejects any other.

  • Open (class, abstract class): any number of unknown children.
  • Sealed: only the children named in permits.
  • Final: no children at all.

sealed and permits syntax

Put sealed before class and list the allowed children after permits, separated by commas: public abstract sealed class Account permits Savings, Current { }. The parent is usually abstract too, because an account must be one of the kinds, never a plain Account.

Example 2 · A sealed class with its permitted subclasses

SealedAccountDemo.javaJava
import java.util.Arrays;import java.util.List;
abstract sealed class Account permits Savings, Current {    private final String number;    protected final double balance;
    Account(String number, double balance) {        this.number = number;        this.balance = balance;    }
    String number() {        return number;    }
    abstract double monthlyInterest();}
final class Savings extends Account {    Savings(String number, double balance) {        super(number, balance);    }
    @Override    double monthlyInterest() {        return balance * 0.035 / 12;    }}
final class Current extends Account {    Current(String number, double balance) {        super(number, balance);    }
    @Override    double monthlyInterest() {        return 0;    }}
public class SealedAccountDemo {    public static void main(String[] args) {        List<Account> accounts = List.of(new Savings("SB-101", 120000), new Current("CA-202", 450000));        for (Account a : accounts) {            System.out.printf("%s interest: Rs. %.2f%n", a.number(), a.monthlyInterest());        }
        String kinds = Arrays.toString(Arrays.stream(Account.class.getPermittedSubclasses())                .map(Class::getSimpleName)                .toArray());        System.out.println("Allowed kinds: " + kinds);        System.out.println("Is Account sealed? " + Account.class.isSealed());    }}
Output
SB-101 interest: Rs. 350.00
CA-202 interest: Rs. 0.00
Allowed kinds: [Savings, Current]
Is Account sealed? true

What this code does

  • abstract sealed class Account permits Savings, Current names every kind of account. Both children are final, so the whole family is exactly these two classes.
  • Polymorphism works as usual: a.monthlyInterest() runs each child's version. getPermittedSubclasses() and isSealed() (Java 17) let a program read the list at run time.

Each permitted child must directly extend the sealed class, and it must say what happens below it. For now every child is marked final, meaning the hierarchy stops there: final class Savings extends Account. The next lesson covers the other two choices, sealed and non-sealed. Interfaces can be sealed in the same way, sealed interface Shape permits Circle, Square, and a later lesson pairs them with records.

Order of execution

Build a sealed family step by step

Tap the steps in a sensible order.

sealed, permits and non-sealed are contextual keywords: special only in these positions, so old code with a variable named permits still compiles.

Rules: where permitted subclasses must live

The parent and its permitted children must be compiled together and be easy to find. So Java adds a location rule. If the code is in a named module (a project with a module-info.java file), the children must be in the same module. Otherwise, which is the usual case for student projects, they must be in the same package as the sealed class.

The list must also match reality. Every class named in permits must exist and must directly extend the sealed class, or javac reports invalid permits clause. A grandchild cannot be listed; it is permitted by its own sealed parent instead.

  • No module-info.java: parent and children in the same package.
  • With module-info.java: parent and children in the same module.
  • Every permitted class must directly extend the sealed class.
  • Anonymous classes and lambdas cannot extend a sealed type.

The compiler error for a subclass that is not permitted

Try to add a child that is not in the list, like final class Crypto extends Payment, and javac stops with: class is not allowed to extend sealed class: Payment (as it is not listed in its permits clause).

Example 3 · Mistake: extending a sealed class without a permit

NotPermittedDemo.javaJava
abstract sealed class Payment permits Upi, Card { }
final class Upi extends Payment { }
final class Card extends Payment { }
final class Crypto extends Payment { }
public class NotPermittedDemo {    public static void main(String[] args) {        Payment p = new Crypto();        System.out.println(p);    }}
Sample compiler output
NotPermittedDemo.java:7: error: class is not allowed to extend sealed class: Payment (as it is not listed in its permits clause)
final class Crypto extends Payment { }
      ^
1 error

What this code does

  • Crypto is not in the permits list, so javac refuses the class itself. The program never runs, so no payment can ever reach code that does not know about Crypto.
  • To allow it on purpose, add it to the list: permits Upi, Card, Crypto. Then update every method that handles each kind of payment.

Example 4 · Mistake: a permitted class with no modifier

MissingModifierDemo.javaJava
abstract sealed class Ticket permits Sleeper, AcThreeTier { }
final class Sleeper extends Ticket { }
class AcThreeTier extends Ticket { }
public class MissingModifierDemo {    public static void main(String[] args) {        System.out.println(new Sleeper());    }}
Sample compiler output
MissingModifierDemo.java:5: error: sealed, non-sealed or final modifiers expected
class AcThreeTier extends Ticket { }
^
1 error

What this code does

  • A permitted child must state how the hierarchy continues below it: final, sealed or non-sealed. A plain class would let anyone extend AcThreeTier, which would silently reopen the closed family.
  • Here final class AcThreeTier extends Ticket fixes it. The next lesson explains when to choose sealed or non-sealed instead.

The error appears where the class is declared, long before the program runs.

Two more errors are common. A permitted child with no modifier gives sealed, non-sealed or final modifiers expected. An anonymous class like new Payment() { } gives anonymous classes must not extend sealed classes. Each error protects the same promise: the list in permits is the complete list of direct children.

Find the bug

Find the line the compiler rejects

Each snippet is meant to compile. Tap the line that must change, then check the fix.

Triangle must be an allowed shape too.

Round 1 of 3
To add a new kind on purpose, add it to permits and write the class. Then search for code that handles every kind, because it now has one more case.

Example 5 · Handling every permitted kind: train fares

FareDemo.javaJava
import java.util.List;
abstract sealed class Ticket permits Sleeper, AcThreeTier, AcTwoTier {    final String pnr;    final int distanceKm;
    Ticket(String pnr, int distanceKm) {        this.pnr = pnr;        this.distanceKm = distanceKm;    }}
final class Sleeper extends Ticket {    Sleeper(String pnr, int km) {        super(pnr, km);    }}
final class AcThreeTier extends Ticket {    final boolean withBedding;
    AcThreeTier(String pnr, int km, boolean withBedding) {        super(pnr, km);        this.withBedding = withBedding;    }}
final class AcTwoTier extends Ticket {    AcTwoTier(String pnr, int km) {        super(pnr, km);    }}
public class FareDemo {    static int fare(Ticket t) {        if (t instanceof Sleeper) {            return t.distanceKm * 1;        } else if (t instanceof AcThreeTier ac3) {            return t.distanceKm * 2 + (ac3.withBedding ? 60 : 0);        } else if (t instanceof AcTwoTier) {            return t.distanceKm * 3;        }        throw new AssertionError("sealed: no other kind exists");    }
    public static void main(String[] args) {        List<Ticket> tickets = List.of(                new Sleeper("PNR-1", 520),                new AcThreeTier("PNR-2", 520, true),                new AcTwoTier("PNR-3", 520));        for (Ticket t : tickets) {            System.out.println(t.pnr + " " + t.getClass().getSimpleName() + " Rs. " + fare(t));        }    }}
Output
PNR-1 Sleeper Rs. 520
PNR-2 AcThreeTier Rs. 1100
PNR-3 AcTwoTier Rs. 1560

What this code does

  • The sealed list tells the writer of fare exactly which three kinds exist, so the method can handle each one. t instanceof AcThreeTier ac3 is the pattern matching from the OOP module: test and cast in one step.
  • The last line can never run while the list has three kinds, so an AssertionError marks it as impossible. In Java 21, a switch over a sealed type can prove this at compile time; the Pattern Matching module covers it.

Next step

Check your understanding

12 quick questions