Chapter 47 of 77

Sealed Classes in Java

Until now, we have had only two choices when designing a class hierarchy. A class is either open, so that any class anywhere can extend it, or it is final, so that no class can extend it at all.

But many real situations sit in between. Think about the payment options in a shopping app: UPI, card, and cash. We want a common parent type Payment, and we want exactly these three kinds of payment. We do not want some random class elsewhere in the code to quietly add a fourth kind that the rest of the program doesn't know how to handle.

Normal class   → anyone can extend it          (fully open)
sealed class   → only the classes YOU list      (controlled)
final class    → nobody can extend it          (fully closed)

Java 17 added exactly this middle option: sealed classes and sealed interfaces.

A sealed class or interface restricts which classes are allowed to extend or implement it. It lists the permitted subclasses, and the compiler rejects every other class that tries to extend it.

Sealed classes were tried out as a preview feature in Java 15 and 16 and became a standard, permanent feature in Java 17. They work in every version since, including the current LTS release, Java 25.

Basic Syntax

We add the sealed modifier to the parent class and list the allowed children after the permits keyword:

sealed class Parent permits ChildA, ChildB {
    // ...
}

Every permitted subclass must then say what happens below it, by using exactly one of these three modifiers:

Modifier on the subclass

Meaning

final

The hierarchy stops here. Nobody can extend this subclass.

sealed

This subclass can be extended, but only by the classes it lists in its own permits clause.

non-sealed

This subclass is open again. Any class can extend it.

This rule forces you to make a conscious decision for every branch of the hierarchy, instead of leaving it open by accident.

A First Example

Let's model shapes. Our program only knows how to deal with circles, squares, and rectangles, so we seal Shape and permit just those three. We also make Shape abstract, as we learned in the Abstract Classes chapter, because a plain "shape" has no area of its own.

sealed abstract class Shape permits Circle, Square, Rectangle {
    abstract double area();
}

final class Circle extends Shape {
    private final double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    @Override
    double area() {
        return Math.PI * radius * radius;
    }
}

final class Square extends Shape {
    private final double side;

    Square(double side) {
        this.side = side;
    }

    @Override
    double area() {
        return side * side;
    }
}

final class Rectangle extends Shape {
    private final double length, width;

    Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    @Override
    double area() {
        return length * width;
    }
}

class Main {
    public static void main(String[] args) {

        Shape[] shapes = { new Circle(1), new Square(4), new Rectangle(2, 5) };

        for (Shape s : shapes) {
            System.out.printf("%s area = %.2f%n", s.getClass().getSimpleName(), s.area());
        }
    }
}

Output:

Circle area = 3.14
Square area = 16.00
Rectangle area = 10.00

Apart from the sealed, permits, and final keywords, this is ordinary inheritance. Overriding and polymorphism work exactly as before: a Shape reference can hold any of the three objects, and s.area() calls the right version.

The sealed keyword only controls who may extend the class. It does not change how objects are created or how methods are called.

What the Compiler Checks

The real value of a sealed class is that the compiler enforces the list. Let's break the rules on purpose and see what happens.

1. A class that is not permitted tries to extend the sealed class:

sealed abstract class Shape permits Circle, Square {
}

final class Circle extends Shape {
}

final class Square extends Shape {
}

final class Triangle extends Shape {   // not in the permits list
}
error: class is not allowed to extend sealed class: Shape (as it is not listed in its 'permits' clause)

(This is the wording of Java 21 and later. Java 17 prints the same message without the quotes around permits.)

2. A permitted subclass forgets to choose final, sealed, or non-sealed:

sealed abstract class Shape permits Circle, Square {
}

class Circle extends Shape {   // no modifier
}

final class Square extends Shape {
}
error: sealed, non-sealed or final modifiers expected

3. A class is listed in permits but does not actually extend the sealed class:

sealed abstract class Shape permits Circle, Square {
}

final class Circle {   // forgot "extends Shape"
}

final class Square extends Shape {
}
error: invalid permits clause
  (subclass Circle must extend sealed class)

4. Someone tries to sneak in an anonymous class:

Shape s = new Shape() { };
error: anonymous classes must not extend sealed classes

An anonymous class (from the Inner Classes chapter) has no name, so it can never appear in a permits list. For the same reason, a local class declared inside a method cannot extend a sealed class either.

All of these are compile-time errors. The mistake is caught before the program ever runs.

final, sealed and non-sealed Together

Here is a bigger hierarchy that uses all three options. This time the parent class Vehicle is not abstract, which shows that a sealed class can be a normal, concrete class too.

Vehicle (sealed)
 ├── Car          (final)       → closed
 ├── Bike         (sealed)      → only ElectricBike may extend it
 │    └── ElectricBike (final)
 └── Truck        (non-sealed)  → open: anyone may extend it
      └── DumpTruck (a normal class)
sealed class Vehicle permits Car, Truck, Bike {
    String describe() {
        return "A vehicle";
    }
}

final class Car extends Vehicle {
    @Override
    String describe() {
        return "A car";
    }
}

sealed class Bike extends Vehicle permits ElectricBike {
    @Override
    String describe() {
        return "A bike";
    }
}

final class ElectricBike extends Bike {
    @Override
    String describe() {
        return "An electric bike";
    }
}

non-sealed class Truck extends Vehicle {
    @Override
    String describe() {
        return "A truck";
    }
}

// Truck is non-sealed, so any class may extend it
class DumpTruck extends Truck {
    @Override
    String describe() {
        return "A dump truck";
    }
}

class Main {
    public static void main(String[] args) {

        Vehicle[] vehicles = {
            new Vehicle(), new Car(), new Bike(),
            new ElectricBike(), new Truck(), new DumpTruck()
        };

        for (Vehicle v : vehicles) {
            System.out.println(v.describe());
        }

        System.out.println();
        System.out.println("Vehicle sealed? " + Vehicle.class.isSealed());
        System.out.println("Truck sealed?   " + Truck.class.isSealed());

        System.out.print("Vehicle permits:");
        for (Class<?> c : Vehicle.class.getPermittedSubclasses()) {
            System.out.print(" " + c.getSimpleName());
        }
        System.out.println();
    }
}

Output:

A vehicle
A car
A bike
An electric bike
A truck
A dump truck

Vehicle sealed? true
Truck sealed?   false
Vehicle permits: Car Truck Bike

A few things to notice:

  • Bike is itself sealed, so it has its own permits list. Sealing can continue down as many levels as you like.

  • Truck is non-sealed, which re-opens that branch. DumpTruck is a normal class and needed no permission. Use this when you want control at the top level but want to allow extensions in one particular branch.

  • non-sealed is written with a hyphen. It is the first keyword in Java that contains a hyphen.

  • Class objects can tell you whether a class is sealed: isSealed() and getPermittedSubclasses() were added in Java 17. (The Java documentation does not promise any particular order for the permitted classes, so don't rely on it.)

Sealed Interfaces

Interfaces can be sealed in exactly the same way. The permits list names the classes (or interfaces) allowed to implement it. Let's go back to our payment example:

sealed interface Payment permits UpiPayment, CardPayment, CashPayment {
    double amount();
}

final class UpiPayment implements Payment {
    private final String upiId;
    private final double amount;

    UpiPayment(String upiId, double amount) {
        this.upiId = upiId;
        this.amount = amount;
    }

    public double amount() { return amount; }
    String upiId() { return upiId; }
}

final class CardPayment implements Payment {
    private final String lastFourDigits;
    private final double amount;

    CardPayment(String lastFourDigits, double amount) {
        this.lastFourDigits = lastFourDigits;
        this.amount = amount;
    }

    public double amount() { return amount; }
    String lastFourDigits() { return lastFourDigits; }
}

final class CashPayment implements Payment {
    private final double amount;

    CashPayment(double amount) {
        this.amount = amount;
    }

    public double amount() { return amount; }
}

class Main {

    static String receipt(Payment p) {
        if (p instanceof UpiPayment upi) {
            return "Paid Rs. " + upi.amount() + " via UPI (" + upi.upiId() + ")";
        } else if (p instanceof CardPayment card) {
            return "Paid Rs. " + card.amount() + " by card ending " + card.lastFourDigits();
        } else {
            return "Paid Rs. " + p.amount() + " in cash";
        }
    }

    public static void main(String[] args) {
        Payment[] payments = {
            new UpiPayment("ravi@okbank", 250.0),
            new CardPayment("4821", 1200.0),
            new CashPayment(80.0)
        };

        double total = 0;
        for (Payment p : payments) {
            System.out.println(receipt(p));
            total += p.amount();
        }
        System.out.println("Total: Rs. " + total);
    }
}

Output:

Paid Rs. 250.0 via UPI (ravi@okbank)
Paid Rs. 1200.0 by card ending 4821
Paid Rs. 80.0 in cash
Total: Rs. 1530.0

In receipt() we used instanceof with a variable name, such as p instanceof UpiPayment upi, which we first saw in the Polymorphism chapter. Notice the final else: because Payment is sealed, we know that a payment which is neither UPI nor card must be cash. With an open interface, we could never be sure of that.

A few extra rules for sealed interfaces:

  • A class that implements a sealed interface must again be final, sealed, or non-sealed.

  • An interface that extends a sealed interface can be sealed or non-sealed, but not final. Interfaces can never be final, and the compiler reports illegal combination of modifiers: interface and final.

  • Records and enums (you will meet both in later chapters) need no extra modifier here: a record is automatically final, and an enum is automatically final or sealed. You will see in the Pattern Matching chapter that "sealed interface + records" is a very popular combination.

Leaving Out permits

If the sealed class and all its subclasses are written in the same source file, you can skip the permits clause. The compiler then treats every direct subclass in that file as permitted:

sealed interface Animal {      // no permits clause
}

final class Dog implements Animal {
}

final class Cat implements Animal {
}

Here Animal.class.getPermittedSubclasses() would give Dog and Cat. If a sealed class ends up with no subclasses at all, that is an error too:

error: sealed class must have subclasses

Where Can Permitted Subclasses Live?

A sealed class and its permitted subclasses must stay close together, so that the compiler can see and check all of them:

  • Each permitted subclass must directly extend the sealed class (or directly implement the sealed interface).

  • In an ordinary program, the permitted subclasses must be in the same package as the sealed class. (If your code is organised as a Java module, they must be in the same module instead.) You will learn about packages in the next chapter.

  • The permitted subclasses must exist when the sealed class is compiled. You cannot permit a class that you plan to write "some day".

Why Use Sealed Classes?

1. You control your design. If you are writing a library, a sealed type promises your users "these are all the kinds there are". Nobody can add a strange subclass that breaks your assumptions.

2. The compiler knows every subtype. This is the biggest benefit. Since the list is fixed, the compiler can check that your code handles every case. In the Pattern Matching chapter, you will see a switch like this, with no default branch (Java 21 and later). There, the shapes are written as records, which give us accessor methods like radius() and side() automatically:

double area = switch (shape) {
    case Circle c    -> Math.PI * c.radius() * c.radius();
    case Square s    -> s.side() * s.side();
    case Rectangle r -> r.length() * r.width();
};

If someone later adds a Triangle to the permits list, every such switch that forgets the new case stops compiling. Instead of a bug in production, you get a list of places to fix.

3. It documents intent. Reading sealed interface Payment permits UpiPayment, CardPayment, CashPayment tells another developer immediately what all the possible payments are, without searching the whole project.

Sealed Class vs Enum

An enum (which you will meet in a later chapter) also represents a fixed set of choices, so students often mix the two up. The difference is what is fixed:

Feature

Enum

Sealed class / interface

What is fixed?

The set of objects (constants)

The set of subclasses (types)

Objects per kind

Exactly one per constant

As many as you create

Different fields per kind?

No, all constants share the same fields

Yes, each subclass has its own fields

Example

Day.MONDAY, Day.TUESDAY

A UPI payment has a UPI id; a card payment has card digits

Use an enum when every choice carries the same kind of data. Use a sealed hierarchy when the choices need different data.

Comparing the Options

Class declared as

Who can extend it?

Typical use

Normal class

Any class

General-purpose base classes

final

No class

Classes that must not change, like String

sealed ... permits

Only the listed classes

A fixed family of types, like shapes or payment kinds

non-sealed

Any class (only used under a sealed parent)

Re-opening one branch of a sealed hierarchy

abstract

Any class (can be combined with sealed)

A base type with no objects of its own

Common Mistakes

  • Forgetting the modifier on a subclass. Every permitted subclass needs final, sealed, or non-sealed (records and enums get one automatically).

  • Writing nonsealed or non_sealed. The keyword is non-sealed, with a hyphen.

  • Listing a class in permits that doesn't extend the parent. Each permitted class must directly extend the sealed class.

  • Putting subclasses in a different package. Outside of modules, permitted subclasses must be in the same package as the sealed class.

  • Thinking sealed means final. A sealed class can have subclasses (it must have at least one), and it can even be a concrete class with its own objects.

  • Making a sub-interface final. An interface under a sealed interface can only be sealed or non-sealed.

Interview Tips

  • What is a sealed class? A class or interface that restricts which classes can extend or implement it, using sealed and permits. Standard since Java 17 (JEP 409).

  • What modifiers must a permitted subclass have? Exactly one of final, sealed, or non-sealed.

  • Why not just use final or package-private classes? final allows no subclasses at all. Package-private access hides the parent type from other packages, so outside code cannot even use it as a type. A sealed class can be fully public and usable everywhere while still limiting who extends it.

  • What is the main practical benefit? Exhaustiveness: because the compiler knows all subtypes, a switch over a sealed type can cover every case without a default, and adding a new subtype causes compile errors where cases are missing.

  • Can a record extend a sealed class? No, a record (covered in the Records chapter) cannot extend any class. But a record can implement a sealed interface, and it is implicitly final.

The Main Idea

A sealed class says "only these classes may extend me". It sits between a normal class (anyone can extend) and a final class (no one can extend).

Key points to remember:

  • Declare it with sealed and list children with permits.

  • Each permitted child must be final, sealed, or non-sealed.

  • Interfaces can be sealed too, and records fit them perfectly.

  • The compiler rejects any class that isn't on the list.

  • The fixed list lets the compiler check that your code handles every subtype.