00:00

Sealed Classes and Interfaces in Java 17

Last updated: · Standard (Java 17)

A sealed class or sealed interface restricts which other classes may extend or implement it. You list the allowed subtypes with permits. Sealed types were previewed in Java 15 and 16 and became a standard feature in Java 17 (JEP 409).

This tutorial explains the problem sealed types solve, the rules for permitted subclasses, and how they work together with records and pattern matching.

1. Why Are Sealed Classes Needed?

Before Java 17 you could only make a class final (nobody may extend it) or leave it open (anybody may). Many domains have a fixed set of variants, such as vehicle types or payment states. Sealed types let you say "exactly these subtypes and no others", which documents the design and lets the compiler check code that handles every case.

2. Syntax and Rules

Vehicle.java
public sealed interface Vehicle permits Car, Truck, Bike { }

public record Car(int seats) implements Vehicle { }          // implicitly final
public final class Truck implements Vehicle { }               // final
public non-sealed class Bike implements Vehicle { }            // open again
  • Every permitted subclass must be final, sealed or non-sealed.
  • Permitted subclasses must be in the same module, or in the same package if you do not use modules.
  • If all subclasses are in the same source file, the permits clause can be omitted; the compiler infers it.
  • A class not listed in permits cannot extend the sealed type.

3. Practical Examples

Example 1: A sealed interface with records

SealedVehicles.java
public class SealedVehicles {
    // Only Car, Truck and Bike may implement Vehicle
    sealed interface Vehicle permits Car, Truck, Bike { }

    record Car(int seats) implements Vehicle { }            // records are implicitly final
    record Truck(double loadTonnes) implements Vehicle { }
    record Bike() implements Vehicle { }

    // Toll rules can rely on the closed set of vehicle types
    static int toll(Vehicle v) {
        if (v instanceof Car c) {
            return c.seats() > 5 ? 120 : 80;
        } else if (v instanceof Truck t) {
            return 200 + (int) (t.loadTonnes() * 25);
        } else if (v instanceof Bike) {
            return 20;
        }
        throw new AssertionError("impossible: Vehicle is sealed");
    }

    public static void main(String[] args) {
        Vehicle[] queue = { new Car(4), new Car(7), new Truck(8.5), new Bike() };
        for (Vehicle v : queue) {
            System.out.println(v + " -> toll " + toll(v));
        }
    }
}
Output
Car[seats=4] -> toll 80
Car[seats=7] -> toll 120
Truck[loadTonnes=8.5] -> toll 412
Bike[] -> toll 20

Because Vehicle is sealed, the three instanceof branches cover every possible type. In Java 21 this becomes a switch that the compiler checks for completeness.

Example 2: final, sealed and non-sealed subclasses

SealedClassHierarchy.java
public class SealedClassHierarchy {
    // A sealed abstract class
    static abstract sealed class Account permits Savings, Current, Loan { }

    static final class Savings extends Account { }          // final: closes this branch

    static sealed class Current extends Account permits Overdraft { }   // sealed: further restricted
    static final class Overdraft extends Current { }

    static non-sealed class Loan extends Account { }        // non-sealed: open again
    static class HomeLoan extends Loan { }                  // anyone may extend Loan

    public static void main(String[] args) {
        System.out.println("Account sealed? " + Account.class.isSealed());
        for (Class<?> c : Account.class.getPermittedSubclasses()) {
            String kind = java.lang.reflect.Modifier.isFinal(c.getModifiers()) ? "final"
                    : c.isSealed() ? "sealed" : "non-sealed";
            System.out.println("  permits " + c.getSimpleName() + " (" + kind + ")");
        }
        System.out.println("HomeLoan is an Account: " + (new HomeLoan() instanceof Account));
    }
}
Output
Account sealed? true
  permits Savings (final)
  permits Current (sealed)
  permits Loan (non-sealed)
HomeLoan is an Account: true

Class.isSealed() and getPermittedSubclasses() were added for reflection. Loan is non-sealed, so HomeLoan can extend it freely.

Example 3: Extending without permission

NotPermitted.java
public class NotPermitted {
    sealed interface Shape permits Circle { }
    record Circle(double r) implements Shape { }

    // Square is not listed in "permits"
    record Square(double side) implements Shape { }

    public static void main(String[] args) {
        System.out.println(new Square(2));
    }
}
Compiler output
NotPermitted.java:6: error: class is not allowed to extend sealed class: Shape (as it is not listed in its 'permits' clause)
    record Square(double side) implements Shape { }
    ^
1 error

4. How the Hierarchy Is Restricted

A sealed hierarchy The sealed type Account permits Savings, Current and Loan. Savings is final, Current is sealed and permits only Overdraft, and Loan is non-sealed so any class may extend it. sealed Account permits 3 types final Savings no subclasses sealed Current permits Overdraft non-sealed Loan open to all
Figure 1: Each permitted subclass decides how far the hierarchy may continue.

5. Important Points and Best Practices

  • Combine sealed interfaces with records to model data with a fixed set of shapes.
  • Use non-sealed only when you deliberately want an extension point.
  • Sealing does not affect access modifiers; a sealed class can still be public.
  • Adding a new permitted subtype is a breaking change for code that handles all cases, which is usually what you want: the compiler shows every place to update.

6. Summary

  • Sealed classes and interfaces became standard in Java 17 (JEP 409).
  • The permits clause lists the only allowed direct subtypes.
  • Each subtype must be final, sealed or non-sealed.
  • Sealed types work hand in hand with records and pattern matching.

Related Tutorials

7. References