Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 201 ยท Object-Oriented Programming

Sealed Classes and Interfaces

Learn Java sealed classes and interfaces - sealed, permits, final and non-sealed subclasses, records as subtypes, exhaustive switches and modeling closed hierarchies.

When you design a class hierarchy, Java has traditionally given you two choices. Mark a class final and nobody can extend it. Leave it open and anybody can extend it, anywhere, forever. Many real designs sit in between: a payment is a card payment, a bank transfer or a voucher, and nothing else. A shape in your drawing app is a circle, a rectangle or a triangle. You want subclasses, but only the ones you wrote.

Sealed classes and interfaces (Java 17) express exactly that. A sealed type lists the classes that may extend it, and the compiler rejects every other attempt. Because the compiler knows the complete list, it can also check that a switch handles every case, with no default branch needed. This lesson covers the syntax, the rules every permitted subclass must follow, sealed interfaces with records, exhaustive switches, the compile errors you'll meet, and how to use sealed types to model data.

The problem sealed types solve

Imagine a Shape hierarchy with three kinds of shapes. Code all over the program asks "which shape is this?" and computes areas, draws outlines or saves files. If Shape is an open class, someone can add class Hexagon extends Shape in another part of the code base, and every one of those places silently ignores hexagons, or falls into a default branch that throws at run time.

Before Java 17, people approximated a closed hierarchy with tricks: a package-private constructor (so only classes in the same package can extend it) or a comment saying "please don't extend this." Neither is visible to the compiler as a list of subclasses, so neither helps it check your code. A sealed class turns the design decision into something the compiler enforces.

Declaring a sealed class

Add the sealed modifier and a permits clause naming the allowed direct subclasses:

Java
public sealed class Vehicle permits Car, Truck, Bicycle {
    // ...
}

Every class listed in permits must:

  1. directly extend the sealed class (a grandchild can't be listed);
  2. say how it continues the hierarchy, with exactly one of three modifiers:
    • final: no further subclasses;
    • sealed: its own closed list of subclasses, with its own permits;
    • non-sealed: open again, anyone may extend it;
  3. live in the same module as the sealed class, or, if you aren't using modules (the common case for small programs), in the same package.
Java final, sealed and non-sealed subclasses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The hierarchy is closed at the top (only Car, Truck and Bicycle extend Vehicle), closed again under Truck, and deliberately open under Bicycle. CargoBike needs no special modifier: Bicycle is a normal, open class now.

The modifier on each subclass isn't optional. If you write static class Car extends Vehicle without final, sealed or non-sealed, the compiler stops with sealed, non-sealed or final modifiers expected. Java forces the author of each subclass to make a conscious choice about what comes below it.

sealed can be combined with abstract, as Vehicle shows. In fact most sealed classes are abstract, because the interesting objects are the concrete subclasses. (The examples nest the classes inside Main so everything fits in one file; static nested classes behave like top-level classes here. See Nested, Inner, Local and Anonymous Classes.)

When you can leave out permits

If the sealed class and all of its subclasses are declared in the same source file, you may omit permits. The compiler then permits exactly the subclasses it finds in that file:

Java
sealed interface Token { }                       // no permits clause
record Num(double value) implements Token { }
record Operator(char symbol) implements Token { }
record Paren(boolean open) implements Token { }

This is handy for small hierarchies that belong together. For larger ones spread over several files, the explicit permits list doubles as documentation: open the parent and you see every child.

Sealed interfaces and records

Interfaces can be sealed too, and that's the form you'll use most. A sealed interface lists the classes that may implement it (and the interfaces that may extend it). Records are a perfect fit: a record is implicitly final, so it satisfies the "final, sealed or non-sealed" rule with no extra keyword. Enums are implicitly final or sealed as well, so they can implement sealed interfaces directly.

Java A sealed interface with records and an exhaustive switch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look at area. The switch has one case per permitted type and no default. Because Shape is sealed, the compiler can prove that every possible Shape is a Circle, a Rectangle or a Triangle, so the switch is exhaustive. (A null shape throws NullPointerException, as with any switch that has no case null.)

case Circle c is a type pattern: it tests the type and binds the variable c in one step. Pattern Matching covers type patterns, record patterns and guards in depth; for now, notice what the sealed hierarchy gives you.

Why exhaustiveness matters

Suppose you later add a fourth shape:

Java
sealed interface Shape permits Circle, Rectangle, Triangle, Hexagon { }
record Hexagon(double side) implements Shape { }

Now every switch over Shape that lacks a Hexagon case stops compiling, with the switch expression does not cover all possible input values. That's the point. Instead of a bug hidden in some rarely used method, you get a list of compile errors showing every place that needs updating. With an open class and a default -> throw ... branch, the same mistake would only show up when a user happens to trigger it.

A default branch on a switch over a sealed type quietly gives this protection up: it also matches the new Hexagon. When you switch over a sealed type, list the cases and leave default out.

What the compiler enforces

The rules are checked at compile time. Here are the most common violations in one file; this example fails to compile on purpose:

Java Breaking the sealed rules (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The compiler reports two errors. For Voucher: class is not allowed to extend sealed class: Payment (as it is not listed in its 'permits' clause). For the anonymous class: anonymous classes must not extend sealed classes. Anonymous and local classes have no name you could put in permits, so they're always rejected. Fix the first error by adding Voucher to the permits list; fix the second by using one of the permitted types.

There are two more rules worth knowing:

  • A permitted subclass must actually extend the sealed type. Listing permits Card, Transfer, Voucher while Voucher doesn't implement Payment is an error too: invalid permits clause, with the note (record Voucher must extend sealed interface). The list and the hierarchy must match exactly.
  • The compiler uses the list for casts. If a sealed interface's permitted classes are all final and none of them implements Runnable, then no Payment can ever be a Runnable, and a cast like (Runnable) payment is rejected as incompatible types. With an open interface, that cast would compile, because some unknown class might implement both.

Inspecting a sealed hierarchy at run time

Reflection exposes the list too. Class.isSealed() tells you whether a class or interface is sealed, and getPermittedSubclasses() returns the permitted direct subtypes (or null if the type isn't sealed). Frameworks use this, for example, to serialize sealed hierarchies to JSON without extra configuration.

Java isSealed and getPermittedSubclasses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice that Stop is an enum. An enum that implements a sealed interface is a convenient way to add "constant" cases (a fixed command, a singleton state) next to record cases that carry data.

Modeling data with sealed types

A sealed interface plus records gives Java what functional languages call an algebraic data type: a value is one of a fixed set of variants (the sealed interface), and each variant is a group of fields (a record). This style is excellent for messages, events, parse results, configuration values and syntax trees, anywhere the set of variants is part of the design.

Here's a small JSON-like value type. Each variant is a record, one of them refers back to the sealed interface (a list of values), and a single recursive method renders any value:

Java A JSON-like value type built from sealed records

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The renderer is one method with one case per variant, and the compiler guarantees it handles them all. Compare that with the classic object-oriented approach, where each class would override an abstract render() method.

Sealed switch or overridden method?

Both are valid, and they're good at different things:

Abstract method overridden in each subclass switch over a sealed type
Adding a new variant Easy: write one new class Every switch must be updated (the compiler lists them)
Adding a new operation Every class must be edited Easy: write one new method with a switch
Logic lives Spread across the subclasses In one place per operation
Best when Variants change often, operations are few and stable Variants are fixed, operations keep growing (render, validate, save, ...)

For a closed set of data variants that many parts of the program interpret differently, the sealed switch usually wins. For a behavior-rich hierarchy where each subclass is "an object that knows how to do things," polymorphism (Polymorphism and Method Overriding) is still the natural tool. You can mix them: a sealed interface can still declare abstract methods that every record implements.

Design guidelines

  • Seal what you own and understand. Seal a hierarchy when the set of subtypes is part of the meaning of the type: the states of an order, the kinds of a token, the results of an operation (Success or Failure).
  • Prefer an enum when variants carry no data. If every case is just a name (RED, GREEN, BLUE), an enum is simpler. Reach for a sealed interface when different cases hold different fields.
  • Use non-sealed sparingly. It's an escape hatch for an intentional extension point. Every non-sealed branch means switches over it can't be exhaustive without handling the open part with a broader case.
  • Adding a permitted subtype is a breaking change. For your own application, that's a feature (the compiler finds every affected switch). For a published library, it breaks your users' exhaustive switches, so plan the variant list carefully before release.
  • Sealing isn't security. It controls the compiler and the JVM's class loading checks, not who can read or call your code. Combine it with access modifiers as usual.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given sealed class Animal permits Dog, Cat { }, which declaration of Dog compiles?

    A permitted subclass must directly extend the sealed class and declare final, sealed or non-sealed. A plain or abstract class without one of those modifiers is rejected, and a class that doesn't extend Animal makes the permits clause invalid.
  2. 2. A sealed interface Shape permits three records, and a switch expression over Shape has one case per record and no default. What happens when you add a fourth permitted record?

    The switch was exhaustive only because the compiler knew all permitted types. With a new one, it reports that the switch does not cover all possible input values, pointing you to every place that needs a new case.
  3. 3. When may you leave out the permits clause?

    If every permitted subclass is declared in the same compilation unit, the compiler infers the list from the file. Otherwise you must list them explicitly.
  4. 4. In sealed interface Vehicle permits Car, Bike {} with non-sealed class Bike implements Vehicle {}, which is true?

    non-sealed reopens that branch of the hierarchy. Subclasses of Bike are allowed anywhere, and since they extend Bike they are also Vehicles, so the set of Vehicle types is no longer fully closed below Bike.
  5. 5. Why can't an anonymous class implement a sealed interface?

    Permitted subclasses must be named in permits (or found by name in the same file). Anonymous and local classes have no usable name, so they are never permitted.

Summary

  • A sealed class or interface lists its allowed direct subtypes with permits; any other subclass is a compile error.
  • Every permitted subclass must directly extend the sealed type, be in the same module (or package), and be final, sealed or non-sealed. Records and enums are implicitly final, so they fit without extra modifiers.
  • If all subclasses are in the same file, permits can be omitted.
  • A switch over a sealed type that covers every permitted subtype is exhaustive without default, and adding a new subtype turns every incomplete switch into a compile error.
  • Anonymous and local classes can never extend sealed types; isSealed() and getPermittedSubclasses() expose the hierarchy at run time.
  • Sealed interfaces plus records model "one of these variants" data cleanly; choose between a sealed switch and overridden methods depending on whether variants or operations change more often.

Next: Pattern Matching, where you'll take sealed hierarchies apart with type patterns, record patterns, guards and exhaustive switches.