Lesson · Records, Sealed Types & Pattern Matching
Sealed types: a family with a guest list
15 min readSealed Classes & Interfaces
sealed plus permits closes a hierarchy to a known set of children, each of which must be final, sealed or deliberately non-sealed. Closed families give the compiler the full guest list, which is what makes exhaustive switches possible.
The outsider at the door
A shape hierarchy that should contain exactly three kinds is declared with a guest list:
sealed interface Shape permits Circle, Square { } record Circle(double r) implements Shape { } record Square(double s) implements Shape { } class Blob implements Shape { } // predict: does this compile?
Predict: the compiler refuses Blob. sealed states that the set of direct subtypes is closed, and permits names them. Without sealed, any future class could implement Shape and break every assumption built on the family, including the exhaustive switches two lessons from now.
The rules, piece by piece
Four pieces make the door work:
| Piece | Means |
|---|---|
sealed | This type may only be extended or implemented by the types in its permits list |
permits A, B | The closed list of direct subtypes; they must live in the same package (or the same module) |
| Child modifiers | Every permitted child must be final, sealed, or non-sealed; silence is a compile error |
non-sealed | Deliberately reopens that one branch: anyone may extend the child further |
- permits can be omitted when every child is declared in the same file; the compiler infers the list from the compilation unit.
- Records are natural children: they are final by construction and carry the data each case needs, which is the tagged-union shape this chapter builds toward.
- The set is closed, not frozen: adding a child later is a deliberate edit to the permits list, and the compiler then points at every switch that no longer covers the family.
Sealing is information for the compiler. A closed guest list turns 'some unknown subclass might arrive' into 'these exact cases exist', which is the precondition for exhaustive switches, total functions and confident refactoring.
The guest list · child policies and the payoff
Current statement
The parent declares two things at once: it is sealed, and its permits list names the only direct children. Nobody else may implement Shape, in any package, ever, unless the list changes.
The payoff: exhaustive switches
A switch over a sealed family can omit default, because the compiler can verify every case is covered:
static double area(Shape shape) { return switch (shape) { // no default: sealed makes this total case Circle c -> Math.PI * c.r() * c.r(); case Square s -> s.s() * s.s(); }; }
- The compiler knows the complete list of subtypes, so it can check the switch covers them all.
- Add a new permitted child (
Triangle) and this method stops compiling until the case is added: the compiler becomes the checklist. - A
defaultstill compiles but silently swallows the future: for closed families, leaving it out is the point. - Pattern matching (the next lesson) supplies the case syntax in full depth; here the lesson is the check the compiler can perform.
Closed families turn maintenance into compiler work. The day someone extends the family, every incomplete switch becomes a compile error naming the gap, which is the cheapest possible place to discover it.
The sealed playbook
Deciding to close a hierarchy, in order:
- Seal when the set of cases is genuinely known and small: shapes, states, results, commands.
- Declare children where they are easiest to keep: same file, permits omitted, often each a record.
- Choose each child's modifier deliberately:
finalfor leaves,sealedfor a deeper closed branch,non-sealedonly when that arm is truly open to the world. - Write switches without
defaultso the compiler keeps the family honest as it grows. - When the set is not actually closed, do not seal; an open interface is the honest type for an unpredictable set of implementations.
A guest list is a promise about the future: only these, or a deliberate edit. That promise is what lets the compiler check total coverage, and it is the whole reason the feature exists.
sealed closes the door; permits names who may enter
A sealed type enumerates its direct subtypes, and each child must choose final, sealed or non-sealed. The closed set lets the compiler verify exhaustive switches without default, turning every later addition of a case into a list of compile errors instead of a silent gap in behaviour.
Interview angles
What do sealed and permits guarantee?+
That the direct subtypes of a type are exactly the permitted ones (same package or module), each declared final, sealed or non-sealed; nobody else can extend or implement it.
It is a compile-time fact about the shape of a hierarchy, checked where the class is declared. The benefit compounds: the compiler can reason about totality, so exhaustive switches and pattern matches become possible without defaults.
sealed interface Shape permits Circle, Square { } // class Blob implements Shape { } // refused: not on the list
Common misconception: That sealed stops subclassing entirely. final does that for a single class; sealed keeps the family open to exactly the named children, each deciding whether its own branch stays open.
Follow-up: Which three modifiers can a permitted child carry?
Why must each permitted child be final, sealed or non-sealed?+
So sealing is transitive and explicit: the compiler must know for every branch whether the family ends there (final), continues closed (sealed), or reopens (non-sealed).
A child without a modifier would leave the branch open silently, contradicting the closure the parent promised. The compiler refuses it outright (verified message: sealed, non-sealed or final modifiers expected); the choice of modifier is part of the design, recorded in the source.
sealed interface A permits B { } class B implements A { } // compile error: must be final, sealed or non-sealed
Common misconception: That non-sealed is a loophole to avoid. It is a deliberate design statement: this branch is intentionally extensible, and everything above it still counts the branch as known.
Follow-up: What does a non-sealed child allow that a sealed one does not?
When can the permits clause be omitted?+
When all permitted subtypes are declared in the same compilation unit (file); the compiler then infers the list from the declarations it can see.
This is why the idiom 'sealed interface plus its records, one file' is common: the family reads as one unit, the permits list cannot drift from reality, and readers see all cases in one screen.
sealed interface Shape { } // no permits list: same-file children record Circle(double r) implements Shape { }
Common misconception: That omitting permits means the type is open. The children are still exactly the same-file declarations; only the list's visibility changed.
Follow-up: What must hold for a permitted child in a different package?
How does sealing enable exhaustive switches?+
The compiler knows the complete child list, so a switch over the sealed type can be checked for coverage; omitting default is legal and stays correct because coverage is verified.
Adding a child then breaks every non-exhaustive switch with a compile error naming the missing case, which is exactly the maintenance alarm you want. A default clause would compile but would quietly absorb future cases, so closed families usually omit it.
return switch (shape) { case Circle c -> Math.PI * c.r() * c.r(); case Square s -> s.s() * s.s(); }; // total: verified, no default needed
Common misconception: That default is just good defensive style. Here it defeats the feature: defaults hide exactly the omissions the seal was added to catch.
Follow-up: What changes about that switch after a Triangle child is permitted?
Sealed types versus enums: what is the difference?+
An enum is a closed set of constant singleton values; a sealed family is a closed set of types, each of which can carry different data and behaviour and can have many instances.
States with no extra data are enums; cases that each carry different fields (Circle has r, Rectangle has w and h) are records under a sealed interface. The two combine: closed sets all the way down, and exhaustive switches all the way across.
enum State { OPEN, CLOSED } // fixed values, same shape sealed interface Result permits Ok, Err { } // fixed cases, different data
Common misconception: That sealed interfaces replace enums. They are the richer variant for cases whose payloads differ; enums stay the right tool for flat constant sets.
Follow-up: When would a sealed hierarchy of records beat an enum with a payload field?