Sealed classes and interfaces

A sealed class or interface lists exactly which classes may extend it. The compiler and the JVM then both know every possible subtype, which lets a switch be checked for completeness. This page explains how sealing is recorded and enforced, shows each modifier, the compiler's errors, sealed types compared with enums, and what happens when a sealed hierarchy changes after clients were compiled.

Contents

What sealing means and how it is enforced

Before Java 17 a class had two choices: open to any subclass, or final and closed to all. Many designs need something in between: "a shape is a circle, a square or a triangle, and nothing else". The old workaround, an abstract class with a package-private constructor, still allowed subclasses in the same package and told the compiler nothing. A sealed class or interface states the set directly in a permits clause.

Sealing is recorded in the class file. The compiler writes a PermittedSubclasses attribute listing the allowed subtypes, which javap -v shows and Class.getPermittedSubclasses() returns. The rule is then checked twice:

  • At compile time, javac rejects any class that extends the sealed type without being listed, and any listed class that does not say how its own branch continues.
  • At class loading, the JVM rejects a class whose superclass or interface is sealed and does not list it, with IncompatibleClassChangeError. So the restriction also holds for code compiled separately or generated at run time.

Because the set of subtypes is known, a switch over a sealed type can be checked for exhaustiveness: covering every permitted subtype is enough, without a default. Combined with records this gives what functional languages call algebraic data types: a record is a "this and that" (a product of fields), and a sealed interface is a "this or that" (a sum of alternatives).

The modifiers of a sealed hierarchy
ModifierUsed onMeaningBest for
sealed ... permits A, BThe parent, or a subtypeOnly the listed types may extend itClosed sets of alternatives
finalA permitted classNo further subclasses (records and enums are implicitly final)Leaf cases
non-sealedA permitted class or interfaceOpen again: any class may extend itAn extension point inside a closed set

History: sealed classes were previewed in Java 15 (JEP 360) and Java 16 (JEP 397) and became standard in Java 17 (JEP 409). Exhaustive pattern-matching switches over them became standard in Java 21 (JEP 441). Sealing itself needs Java 17, the switches below need Java 21, and all outputs were captured on JDK 21.

Declaring a hierarchy with final, sealed and non-sealed

The program builds one branch of each kind: Car is final, Truck is sealed and permits only DumpTruck, and Bike is non-sealed and is extended by Tricycle and an anonymous class. Reflection then reports what it sees, and the wheels of one vehicle per branch are added up: 4 + 10 + 3 + 2.

Java
import java.util.Arrays;

public class SealedHierarchy {

    // Only the three listed classes may extend Vehicle
    abstract static sealed class Vehicle permits Car, Truck, Bike {
        abstract int wheels();
    }

    // final: the branch stops here
    static final class Car extends Vehicle {
        int wheels() {
            return 4;
        }
    }

    // sealed: the branch continues, but only with the listed subclasses
    static sealed class Truck extends Vehicle permits DumpTruck {
        int wheels() {
            return 6;
        }
    }

    static final class DumpTruck extends Truck {
        @Override
        int wheels() {
            return 10;
        }
    }

    // non-sealed: anyone may extend this branch again
    static non-sealed class Bike extends Vehicle {
        int wheels() {
            return 2;
        }
    }

    static class Tricycle extends Bike {
        @Override
        int wheels() {
            return 3;
        }
    }

    static String names(Class<?>[] classes) {
        return Arrays.toString(Arrays.stream(classes).map(Class::getSimpleName).toArray());
    }

    public static void main(String[] args) {
        for (Class<?> c : new Class<?>[] {Vehicle.class, Truck.class, Bike.class, Car.class}) {
            System.out.printf("%-8s sealed=%-5b permitted=%s%n", c.getSimpleName(), c.isSealed(),
                    c.isSealed() ? names(c.getPermittedSubclasses()) : "-");
        }

        Vehicle[] fleet = {new Car(), new DumpTruck(), new Tricycle(), new Bike() {
            // An anonymous subclass is allowed only below the non-sealed Bike
        }};
        int total = 0;
        for (Vehicle v : fleet) {
            total += v.wheels();
        }
        System.out.println("total wheels in the fleet: " + total);
    }
}

Output:

Output
Vehicle  sealed=true  permitted=[Car, Truck, Bike]
Truck    sealed=true  permitted=[DumpTruck]
Bike     sealed=false permitted=-
Car      sealed=false permitted=-
total wheels in the fleet: 19
  • Only Vehicle and Truck report sealed=true. Car is final, which is a different property, and isSealed is false for it.
  • Bike reports sealed=false because non-sealed really does reopen the branch. That is why Tricycle and the anonymous Bike subclass compile, while an anonymous subclass of Vehicle would not.
  • The total is 19. Sealing restricts who may extend a type, not who may use it: any code can hold a Vehicle and call wheels().

What the compiler checks

To show the real messages, the program compiles four small sources in memory with the javax.tools API and prints each diagnostic. All use the same sealed Shape interface with three record implementations, which is the most common shape of a sealed hierarchy.

Java
import java.net.URI;
import java.util.List;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;

// Compiles small sources in memory and prints what javac says about them
public class CompilerChecks {

    static void compile(String label, String code) {
        JavaFileObject file = new SimpleJavaFileObject(URI.create("string:///Demo.java"),
                JavaFileObject.Kind.SOURCE) {
            @Override
            public CharSequence getCharContent(boolean ignore) {
                return code;
            }
        };
        JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
        DiagnosticCollector<JavaFileObject> diags = new DiagnosticCollector<>();
        boolean ok = javac.getTask(null, null, diags, List.of("-d", System.getProperty(
                "java.io.tmpdir")), null, List.of(file)).call();
        System.out.println(label + ": " + (ok ? "compiles" : "error"));
        diags.getDiagnostics().forEach(d -> System.out.println("    " + d.getMessage(null)));
    }

    public static void main(String[] args) {
        String shapes = """
                sealed interface Shape permits Circle, Square, Hexagon {}
                record Circle(double r) implements Shape {}
                record Square(double side) implements Shape {}
                record Hexagon(double side) implements Shape {}
                """;

        compile("switch handles all three shapes", shapes + """
                class Demo {
                    static String name(Shape s) {
                        return switch (s) {
                            case Circle c -> "circle";
                            case Square q -> "square";
                            case Hexagon h -> "hexagon";
                        };
                    }
                }
                """);

        compile("switch forgets Hexagon", shapes + """
                class Demo {
                    static String name(Shape s) {
                        return switch (s) {
                            case Circle c -> "circle";
                            case Square q -> "square";
                        };
                    }
                }
                """);

        compile("class outside the permits list", shapes + """
                class Demo {}
                record Triangle(double b, double h) implements Shape {}
                """);

        compile("permitted subclass without a modifier", """
                sealed class Animal permits Dog {}
                class Dog extends Animal {}
                class Demo {}
                """);
    }
}

Output (each message is javac's own text):

Output
switch handles all three shapes: compiles
switch forgets Hexagon: error
    the switch expression does not cover all possible input values
class outside the permits list: error
    class is not allowed to extend sealed class: Shape (as it is not listed in its 'permits' clause)
permitted subclass without a modifier: error
    sealed, non-sealed or final modifiers expected
  1. A switch with a case for all three shapes compiles with no default, because the permits clause says nothing else can implement Shape.
  2. Without the Hexagon case it fails with "does not cover all possible input values". This is the main payoff: add a type to permits and every switch that forgot it fails to compile, instead of silently reaching a default branch at run time.
  3. A class that is not listed cannot implement the interface, and the message names the permits clause.
  4. A permitted class with none of the three modifiers is rejected with "sealed, non-sealed or final modifiers expected". Records need no modifier because they are implicitly final.

Sealed types compared with enums

An enum and a sealed interface both describe a closed set, but of different things. The program models payment methods both ways, using a card, a bank transfer and cash because each needs different data. It also leaves out the permits clause to show the compiler inferring it.

Java
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

public class EnumVsSealed {

    // An enum: a fixed set of INSTANCES, all with the same fields
    enum Method {
        CARD, BANK_TRANSFER, CASH
    }

    // A sealed interface: a fixed set of TYPES, each with its own data.
    // No permits clause: the compiler infers it from the subtypes in this file
    sealed interface Payment {
        BigDecimal amount();
    }

    record Card(BigDecimal amount, String last4) implements Payment {
    }

    record BankTransfer(BigDecimal amount, String iban) implements Payment {
    }

    record Cash(BigDecimal amount) implements Payment {
    }

    static BigDecimal fee(Method m, BigDecimal amount) {
        return switch (m) {                        // exhaustive over the enum constants
            case CARD -> amount.multiply(new BigDecimal("0.029"));
            case BANK_TRANSFER -> new BigDecimal("0.50");
            case CASH -> BigDecimal.ZERO;
        };
    }

    static String describe(Payment p) {
        return switch (p) {                        // exhaustive over the permitted types
            case Card c -> "card ending " + c.last4();
            case BankTransfer t -> "transfer from " + t.iban().substring(0, 4) + "...";
            case Cash c -> "cash";
        };
    }

    public static void main(String[] args) {
        System.out.println("enum constants: " + Arrays.toString(Method.values()));
        System.out.println("card fee on 100: " + fee(Method.CARD, new BigDecimal("100")));

        System.out.println("inferred permits: " + Arrays.stream(
                Payment.class.getPermittedSubclasses()).map(Class::getSimpleName).toList());
        List<Payment> payments = List.of(
                new Card(new BigDecimal("25.00"), "4242"),
                new BankTransfer(new BigDecimal("900.00"), "DE89370400440532013000"),
                new Cash(new BigDecimal("12.50")));
        for (Payment p : payments) {
            System.out.printf("%-22s %8s%n", describe(p), p.amount());
        }
    }
}

Output:

Output
enum constants: [CARD, BANK_TRANSFER, CASH]
card fee on 100: 2.900
inferred permits: [Card, BankTransfer, Cash]
card ending 4242          25.00
transfer from DE89...    900.00
cash                      12.50
  • The enum has exactly three instances, and every one has the same fields. It suits labels and states: CARD can select a fee rule (2.9% of 100 is 2.900), but it cannot carry the card's last four digits.
  • The sealed interface has exactly three types, and each can have any number of instances with its own data: a card has last4, a transfer has an IBAN, cash has neither.
  • The permits clause was omitted, and getPermittedSubclasses still lists Card, BankTransfer and Cash. When all subtypes are in the same source file, the compiler infers the list in declaration order.
  • Both switches are exhaustive without default. Switching on enum constants has been checked this way since switch expressions arrived in Java 14; switching on sealed types needs the type patterns of Java 21.

Enums can implement a sealed interface too, which mixes both: sealed interface Op permits BinaryOp, UnaryOp with enum BinaryOp implements Op { PLUS, MINUS }.

Modeling a result type

A sealed interface with record cases models "one of these, and nothing else". The Result type is either Ok with a value or Err with a message, so a caller must handle both. The inputs are a valid port, one with spaces, a number above the 65,535 limit, and text that is not a number.

Java
import java.util.List;

public class ResultType {

    // A value that is either a success or a failure, and nothing else
    sealed interface Result<T> permits Ok, Err {
    }

    record Ok<T>(T value) implements Result<T> {
    }

    record Err<T>(String message) implements Result<T> {
    }

    static Result<Integer> parsePort(String text) {
        try {
            int port = Integer.parseInt(text.trim());
            if (port < 1 || port > 65535) {
                return new Err<>(port + " is outside 1-65535");
            }
            return new Ok<>(port);
        } catch (NumberFormatException e) {
            return new Err<>("'" + text + "' is not a number");
        }
    }

    public static void main(String[] args) {
        for (String input : List.of("8080", " 443 ", "70000", "http")) {
            String message = switch (parsePort(input)) {
                case Ok<Integer>(Integer port) -> "port " + port;
                case Err<Integer>(String why) -> "error: " + why;
            };
            System.out.printf("%-8s -> %s%n", "[" + input + "]", message);
        }
    }
}

Output:

Output
[8080]   -> port 8080
[ 443 ]  -> port 443
[70000]  -> error: 70000 is outside 1-65535
[http]   -> error: 'http' is not a number

" 443 " was accepted because parsePort trims it first. 70000 parsed as a number but failed the range check, and "http" failed parsing; both came back as Err with a reason instead of an exception. The switch in main needs no default and takes each record apart with a record pattern. Compared with throwing, the possible failure is visible in the method's return type, and forgetting to handle it does not compile.

Changing a sealed hierarchy after clients are compiled

A sealed hierarchy is a promise to every client, and changing it has effects even on code that is not recompiled. The program compiles version 1 of two small libraries into a temporary directory, then compiles version 2 of only some files, and loads the mix with a class loader. One change adds a new shape; the other seals an interface that an existing class already implements.

Java
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

// Compiles code in two steps, changes the sealed type in between, and runs the old classes
public class SeparateCompilation {

    static final JavaCompiler JAVAC = ToolProvider.getSystemJavaCompiler();

    public static void main(String[] args) throws Exception {
        Path dir = Files.createTempDirectory("sealed");

        // Version 1: Shape permits Circle and Square; Report switches over both
        write(dir, "Shape.java", "public sealed interface Shape permits Circle, Square {}");
        write(dir, "Circle.java", "public record Circle(double r) implements Shape {}");
        write(dir, "Square.java", "public record Square(double s) implements Shape {}");
        write(dir, "Report.java", """
                public class Report {
                    public static String name(Shape s) {
                        return switch (s) {
                            case Circle c -> "circle";
                            case Square q -> "square";
                        };
                    }
                }""");
        write(dir, "Legacy.java", "public final class Legacy implements Old {}");
        write(dir, "Old.java", "public interface Old {}");
        compile(dir, "Shape.java", "Circle.java", "Square.java", "Report.java",
                "Old.java", "Legacy.java");
        System.out.println("version 1 compiled: Report knows Circle and Square");

        // Version 2: a new shape is added, Report is NOT recompiled
        write(dir, "Shape.java", "public sealed interface Shape permits Circle, Square, Tri {}");
        write(dir, "Tri.java", "public record Tri(double b, double h) implements Shape {}");
        // Old becomes sealed without listing Legacy, Legacy is NOT recompiled
        write(dir, "Old.java", "public sealed interface Old permits Newer {}");
        write(dir, "Newer.java", "public final class Newer implements Old {}");
        compile(dir, "Shape.java", "Tri.java", "Old.java", "Newer.java");
        System.out.println("version 2 compiled: Tri added, Old sealed");

        try (URLClassLoader loader = new URLClassLoader(new URL[] {dir.toUri().toURL()})) {
            Method name = loader.loadClass("Report").getMethod("name",
                    loader.loadClass("Shape"));
            Object circle = loader.loadClass("Circle").getConstructors()[0].newInstance(1.0);
            Object tri = loader.loadClass("Tri").getConstructors()[0].newInstance(1.0, 2.0);
            System.out.println("old switch, Circle: " + name.invoke(null, circle));
            try {
                name.invoke(null, tri);
            } catch (java.lang.reflect.InvocationTargetException e) {
                System.out.println("old switch, Tri:    " + e.getCause());
            }
            try {
                loader.loadClass("Legacy");
            } catch (IncompatibleClassChangeError e) {
                System.out.println("loading Legacy:     " + e.getClass().getSimpleName()
                        + ": " + e.getMessage());
            }
        }
    }

    static void write(Path dir, String file, String code) throws IOException {
        Files.writeString(dir.resolve(file), code);
    }

    static void compile(Path dir, String... files) {
        List<String> argv = new ArrayList<>(List.of("-d", dir.toString(), "-cp", dir.toString()));
        for (String f : files) {
            argv.add(dir.resolve(f).toString());
        }
        int rc = JAVAC.run(null, null, null, argv.toArray(new String[0]));
        if (rc != 0) {
            throw new IllegalStateException("javac failed");
        }
    }
}

Output:

Output
version 1 compiled: Report knows Circle and Square
version 2 compiled: Tri added, Old sealed
old switch, Circle: circle
old switch, Tri:    java.lang.MatchException
loading Legacy:     IncompatibleClassChangeError: class Legacy cannot implement sealed interface Old
  • The old Report class still handles a Circle. Given a Tri, which did not exist when it was compiled, its exhaustive switch threw MatchException. The compiler inserts this hidden default into every exhaustive pattern switch without a default, so an unexpected subtype fails loudly instead of being ignored.
  • Loading Legacy failed with IncompatibleClassChangeError: "class Legacy cannot implement sealed interface Old". The JVM checks the PermittedSubclasses attribute when it loads a subclass, not only javac.
  • So adding a permitted subtype is a breaking change for anyone who switches over the type, and sealing a published interface breaks every existing implementation. For a public library API, seal from the start or not at all.

Rules and constraints

  • Permitted subclasses must be in the same module as the sealed class. In code that is not in a named module, they must be in the same package.
  • The permits clause may be left out when every subclass is declared in the same source file, as shown above.
  • Each permitted subclass must directly extend or implement the sealed type, and must be final, sealed or non-sealed. Records and enums are implicitly final.
  • Interfaces can be sealed. A permitted sub-interface uses sealed or non-sealed, since interfaces cannot be final.
  • Anonymous classes and lambdas cannot implement a sealed type, because they have no name to list. A sealed functional interface therefore cannot be implemented with a lambda.
  • A non-sealed subtype keeps exhaustiveness for the parent: a switch that has a case for Bike covers Tricycle and every future subclass of Bike.

Which one to use

Choosing how to restrict a type
SituationUse
A fixed set of values with the same fields (states, labels, units)enum
A fixed set of alternatives, each with its own dataSealed interface with record implementations
A closed set where one branch must stay extensibleSealed parent with a non-sealed subtype
A class nobody should extendfinal
A public library interface users implementNeither: keep it open, because sealing it later breaks them
A result that is either a value or an errorSealed Result with Ok and Err records

For the switch side of sealed types, see sealed classes with pattern matching and pattern matching for switch. For records themselves, see Java records.