Sub topic 5
Using Records and Enums as Permitted Subtypes
This chapter assumes you know Java classes and interfaces, the final keyword, the sealed/permits syntax, and the three subclass modifiers final, sealed and non-sealed. It also assumes you have used records and enums at a basic level and have seen switch expressions. Here you learn how records and enums fit the sealed rules, what they can and cannot do, and how to combine them in one hierarchy. Pattern matching with Java 21 syntax is used throughout.
Why records and enums fit sealed hierarchies
Every permitted subclass of a sealed type must declare one of three modifiers: final, sealed or non-sealed. Records and enums mostly satisfy that rule without any modifier:
- A record is implicitly
final, so it ends the hierarchy at that point. - An enum is implicitly
final, unless one of its constants has a class body. In that case the enum is implicitlysealed, and the constant bodies are its permitted subclasses.
This makes the two a natural pair. A record carries data that differs per instance. An enum represents a variant with a fixed set of instances and no per-instance data. A sealed interface can list both kinds as its variants.
| Kind of subtype | Implicit modifier | Can extend a class? | Can implement a sealed interface? |
|---|---|---|---|
| Record | `final` | No (it already extends `java.lang.Record`) | Yes |
| Enum, plain constants | `final` | No (it already extends `java.lang.Enum`) | Yes |
| Enum, constants with bodies | `sealed` | No | Yes |
| Ordinary class | none, you must choose | Yes | Yes |
The last column is the main constraint. Records and enums can only be permitted subtypes of a sealed interface. They cannot be permitted subtypes of a sealed class, because both already have a superclass.
Records as permitted subtypes
A record that implements a sealed interface needs no modifier. The permits clause can name it like any other class:
sealed interface Shape permits Circle, Square, Rectangle {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
record Rectangle(double width, double height) implements Shape {}Some points about records in this role:
- You may write
final recordredundantly. You may not writesealed recordornon-sealed record. Records cannot have subclasses, so those modifiers make no sense and the compiler rejects them. - A record can implement several sealed interfaces at once. It then appears in the
permitslist of each one. - A record can be generic, for example
record Ok<T>(T value) implements Result<T>. Generic sealed types get their own chapter. - Record components are shallowly immutable. A sealed hierarchy of records does not stop a component from holding a mutable
List. If you need real immutability, copy the list in a compact constructor withList.copyOf. - The compiler generates
equals,hashCodeandtoStringfrom the components, so each variant has value semantics. TwoCircle(1.0)instances are equal.
sealed interface Event {
record Login(String user) implements Event {}
record Purchase(String user, int cents) implements Event {
Purchase {
if (cents < 0) throw new IllegalArgumentException("cents must be >= 0");
}
}
}The compact constructor in Purchase validates the data once, at construction. Every code path that later switches over an Event can then rely on that invariant.
Enums as permitted subtypes
An enum can implement a sealed interface. Use this for variants that carry no data of their own and exist as a fixed set of constants:
sealed interface Direction permits Cardinal, Diagonal {}
enum Cardinal implements Direction { NORTH, EAST, SOUTH, WEST }
enum Diagonal implements Direction { NORTH_EAST, SOUTH_EAST, SOUTH_WEST, NORTH_WEST }The sealed interface here has only two permitted subtypes, but they have eight instances between them. A switch can handle them by type or by constant, as the next sections show.
You cannot put any of final, sealed or non-sealed on an enum declaration. The compiler assigns the modifier for you.
Enums with constant bodies
If an enum constant has its own body, the compiler treats the enum as implicitly sealed:
enum Operator {
ADD { int apply(int a, int b) { return a + b; } },
MUL { int apply(int a, int b) { return a * b; } };
abstract int apply(int a, int b);
}Each constant body is an anonymous subclass, and those subclasses are the enum's permitted subclasses. You cannot name them, so this feature rarely matters in everyday code. It does explain why reflection can report an enum as sealed even though you never wrote the keyword.
Mixing records and enums in one hierarchy
A common design uses enums for the parameterless variants and records for the variants with data. This example is complete and runs on Java 21:
public class Main {
sealed interface Outcome {
enum Simple implements Outcome { SUCCESS, TIMEOUT }
record Failure(String reason) implements Outcome {}
}
static String describe(Outcome outcome) {
return switch (outcome) {
case Outcome.Simple.SUCCESS -> "ok";
case Outcome.Simple.TIMEOUT -> "timed out";
case Outcome.Failure f -> "failed: " + f.reason();
};
}
public static void main(String[] args) {
System.out.println(describe(Outcome.Simple.SUCCESS));
System.out.println(describe(Outcome.Simple.TIMEOUT));
System.out.println(describe(new Outcome.Failure("disk full")));
}
}The output is:
ok
timed out
failed: disk fullOutcome has no permits clause. Its subtypes are declared in the same compilation unit, so the compiler infers them: Simple and Failure. That rule has its own section in the previous chapter.
The diagram shows how the hierarchy is structured.
Exhaustive switches over enum and record variants
An enum permitted subtype can be matched in two ways, and both count toward exhaustiveness.
- By type.
case Outcome.Simple smatches every constant ofSimplein one branch. The branch covers the whole enum. - By constant.
case Outcome.Simple.SUCCESSmatches one constant. Java 21 allows qualified enum constant names as case labels even when the selector type is the sealed interface, not the enum. The switch is exhaustive only if every constant of the enum is listed.
The example above uses the second form. Remove the TIMEOUT line and the compiler reports that the switch does not cover all possible input values. Without the sealed interface, a missing constant would silently fall through to a default or throw at runtime.
Choose by type when all constants behave alike. Choose by constant when each one needs distinct handling. You can mix the two styles in one switch for different enums.
static boolean isFinal(Outcome outcome) {
return switch (outcome) {
case Outcome.Simple s -> true;
case Outcome.Failure f -> false;
};
}For records, the switch can match by type as above, or it can deconstruct the components with a record pattern such as case Failure(String reason). Record patterns get their own chapter.
Common errors
Most mistakes in this area come from forgetting that records and enums already have a superclass.
sealed abstract class Vehicle permits Car {}
// Compile error: a record cannot extend a class.
// record Car(String plate) extends Vehicle {}
// Compile error: an enum cannot extend a class.
// enum Kind extends Vehicle { A, B }If you want a record or enum in the hierarchy, make the root a sealed interface, not a sealed class. If the root must be a class, for example to share fields or a constructor, the variants must be ordinary classes.
Other errors you may meet:
sealed recordornon-sealed enum. The modifier is not allowed. Remove it.- Record or enum not in the permits list. If you write an explicit
permitsclause and forget a nested record, the record fails to compile with a message that it is not allowed to extend the sealed interface. Either add it to the clause or drop the clause. - Non-exhaustive constant switch. Listing only some constants of a permitted enum leaves the switch non-exhaustive. List them all, or use a type pattern for the enum.
- Dominated pattern. If a
case Outcome.Simple sbranch appears beforecase Outcome.Simple.SUCCESS, the later label can never match and the compiler rejects it. Put the specific constants first. - Different packages without a module. Permitted subtypes of a sealed type declared in a named module can sit in different packages of that module. In the unnamed module they must share the package of the sealed type. Nested records and enums avoid this problem entirely.
Choosing between a record and an enum for a variant
Pick based on what the variant is:
- Use a record when instances differ by data, or when the number of instances is not fixed.
Failure("disk full")andFailure("timeout")are two values of one variant. - Use an enum when the variant has a closed, known list of instances and no per-instance data.
SUCCESSandTIMEOUTare two singletons. - Use a record with no components when you want a variant without data but also want it to behave like any other type in the hierarchy. A singleton enum constant does the same job and is guaranteed to be a single instance, which also makes
==comparison safe.
Exercise
A sealed interface Cmd should have three variants: Quit and Help, which carry no data, and Echo, which carries a String text. Write one declaration of each variant using nested types with no permits clause. Then say whether a switch over Cmd with case Cmd.Echo e, case Cmd.Quit.INSTANCE and case Cmd.Help.INSTANCE is exhaustive if Quit and Help are single-constant enums.
Show answer
sealed interface Cmd { enum Quit implements Cmd { INSTANCE } enum Help implements Cmd { INSTANCE } record Echo(String text) implements Cmd {} }. Yes, the switch is exhaustive. Each enum has exactly one constant and both constants are listed, so the compiler sees every possible value of Cmd covered.
Exercise
Explain why record Bus(int seats) extends Vehicle {} fails when Vehicle is a sealed abstract class, and give two ways to restructure the code so that a record can still be part of the hierarchy.
Show answer
A record implicitly extends java.lang.Record, and Java classes can have only one superclass, so a record can never extend Vehicle. You can change Vehicle to a sealed interface so that Bus implements it, or you can turn Bus into an ordinary final class that extends Vehicle and write the constructor, accessors, equals and hashCode by hand.