Sub topic 8
Modeling Data Variants with Sealed Interfaces and Records
This chapter assumes you can write Java classes and interfaces, and that you know the basic syntax of records and switch expressions. It also assumes you have seen the sealed, permits, final and non-sealed keywords from earlier chapters. Here you will use them together as a modeling technique. You need Java 21 or later to run the examples.
Two building blocks: "and" types and "or" types
Most data in a program is one of two shapes.
- A value that has several parts at once. A shipping record has a tracking number and a date. This is a product type, and a Java record models it.
- A value that is exactly one of several alternatives. An order is pending or paid or shipped or cancelled. This is a sum type, and a sealed interface models it.
Combining the two gives an algebraic data type (ADT). The sealed interface names the set of alternatives. Each permitted record describes the data that one alternative carries. Because the set is closed, the compiler can check every switch over it.
| Idea | Java construct | What it gives you |
|---|---|---|
| "This AND that" | `record` | Named components, `equals`, `hashCode`, `toString`, deconstruction |
| "This OR that" | `sealed interface` with permitted records | A closed set of variants the compiler knows |
| Processing a variant | `switch` with patterns | Exhaustiveness checking, no `default` needed |
The problem: one class with optional fields
A common first attempt keeps a status flag and a set of fields that only sometimes apply.
import java.time.LocalDate;
enum Status { PENDING, PAID, SHIPPED, CANCELLED }
class Order {
Status status;
String transactionId; // only meaningful when PAID or later
String trackingNumber; // only meaningful when SHIPPED
LocalDate shippedOn; // only meaningful when SHIPPED
String cancelReason; // only meaningful when CANCELLED
}Nothing stops you from building an order with status PENDING and a tracking number, or one with status SHIPPED and no tracking number. Every method that reads these fields must remember which ones are valid for which status. The compiler cannot help, so mistakes show up at runtime as NullPointerExceptions or wrong data.
The goal of ADT modeling is to make illegal states impossible to write. Each variant carries exactly the fields it needs and no others.
The sealed version
import java.time.LocalDate;
import java.util.Objects;
public class OrderDemo {
sealed interface OrderState {
record Pending() implements OrderState {}
record Paid(String transactionId) implements OrderState {
Paid {
Objects.requireNonNull(transactionId, "transactionId");
}
}
record Shipped(String trackingNumber, LocalDate shippedOn) implements OrderState {
Shipped {
Objects.requireNonNull(trackingNumber, "trackingNumber");
Objects.requireNonNull(shippedOn, "shippedOn");
}
}
record Cancelled(String reason) implements OrderState {}
}
static String describe(OrderState state) {
return switch (state) {
case OrderState.Pending() -> "Waiting for payment";
case OrderState.Paid(String id) -> "Paid, transaction " + id;
case OrderState.Shipped(String tracking, LocalDate date) ->
"Shipped on " + date + ", tracking " + tracking;
case OrderState.Cancelled(String reason) -> "Cancelled: " + reason;
};
}
static OrderState pay(OrderState state, String transactionId) {
return switch (state) {
case OrderState.Pending p -> new OrderState.Paid(transactionId);
case OrderState.Paid p -> throw new IllegalStateException("Already paid");
case OrderState.Shipped s -> throw new IllegalStateException("Already shipped");
case OrderState.Cancelled c -> throw new IllegalStateException("Order is cancelled");
};
}
public static void main(String[] args) {
OrderState state = new OrderState.Pending();
System.out.println(describe(state));
state = pay(state, "tx-1001");
System.out.println(describe(state));
state = new OrderState.Shipped("TRK-77", LocalDate.of(2026, 11, 20));
System.out.println(describe(state));
}
}Running it prints:
Waiting for payment
Paid, transaction tx-1001
Shipped on 2026-11-20, tracking TRK-77A few details make this work.
- The
permitsclause is omitted. All four records are declared in the same compilation unit as the interface, so the compiler infers them as the permitted subclasses. - Records are implicitly
final, so each one satisfies the rule that a permitted subclass must befinal,sealedornon-sealed. - Records nested in an interface are implicitly
staticandpublic. Their qualified names areOrderState.Paidand so on. - A
Shippedvalue always has a tracking number and a date, because the compact constructor rejectsnull. NoShippedobject can exist without them. describeandpayhave nodefaultbranch. The compiler checks that all four variants are handled.
The lifecycle as a diagram
The variants form a small state machine. The sealed type defines the states. The pay method above is one of the transitions.
The sealed type does not enforce these arrows. Any code can construct a Shipped directly from a Pending. The type only guarantees that each state carries the right data. Enforcing the transitions is the job of methods like pay.
Record patterns pull the data out
In describe, the pattern OrderState.Paid(String id) does two things in one step. It checks that the value is a Paid, and it binds the component to the variable id. This is a record deconstruction pattern. You can write var instead of the type, as in OrderState.Paid(var id), and the compiler infers it.
Patterns can nest. If a record component is itself a sealed type, a pattern can look inside it. A compiler can still check exhaustiveness through such nested patterns, but nested cases get long quickly, so use them when they stay readable.
You can add a guard with when to refine a case:
static String shippingNote(OrderState state) {
return switch (state) {
case OrderState.Shipped(String t, LocalDate d) when d.isBefore(LocalDate.of(2026, 1, 1)) ->
"Old shipment " + t;
case OrderState.Shipped(String t, LocalDate d) -> "Recent shipment " + t;
default -> "Not shipped";
};
}Here the default is legitimate because the method deliberately treats the other three variants alike. Keep in mind the cost. A default branch silently absorbs any variant you add later, so the compiler will no longer tell you about it. Prefer listing the variants when each one needs a deliberate decision.
Recursive data types
A variant can refer to its own sealed type. This is how you build trees, linked lists and expression languages. A binary tree of integers needs two variants, an empty leaf and a node holding a value and two subtrees.
public class TreeDemo {
sealed interface IntTree {
record Leaf() implements IntTree {}
record Node(IntTree left, int value, IntTree right) implements IntTree {}
}
static int sum(IntTree tree) {
return switch (tree) {
case IntTree.Leaf() -> 0;
case IntTree.Node(IntTree l, int v, IntTree r) -> sum(l) + v + sum(r);
};
}
static int depth(IntTree tree) {
return switch (tree) {
case IntTree.Leaf() -> 0;
case IntTree.Node(var l, var v, var r) -> 1 + Math.max(depth(l), depth(r));
};
}
public static void main(String[] args) {
IntTree tree = new IntTree.Node(
new IntTree.Node(new IntTree.Leaf(), 1, new IntTree.Leaf()),
2,
new IntTree.Node(new IntTree.Leaf(), 3, new IntTree.Leaf()));
System.out.println(sum(tree));
System.out.println(depth(tree));
}
}This prints 6 and then 2. The recursion in sum mirrors the recursion in the data. Each variant gets one case.
Operations live outside the data
In an object-oriented design you would put an abstract describe() method on the base type and override it in each subclass. With sealed types and records you usually do the opposite. The data types stay small and plain, and operations are switch expressions placed in separate methods.
| Row | Methods in each subclass | `switch` over a sealed type |
|---|---|---|
| Adding a new operation | Edit every subclass | Write one new method |
| Adding a new variant | Write one new class | Fix every `switch` that has no `default` |
| Compiler help when a variant is added | None for methods already written elsewhere | Errors at each non-exhaustive switch |
| Best when | The set of operations is open | The set of variants is fixed |
A sealed hierarchy suits the second column. You decided the variants are a closed set, so adding an operation is the common change. Nothing prevents you from mixing both styles. A default method on the sealed interface is fine for behavior that is the same for every variant.
Keeping variants honest
Records give you shallow immutability only. A component that holds a mutable object can still change after construction.
record Invoice(String id, java.util.List<String> lines) {
Invoice {
lines = java.util.List.copyOf(lines);
}
}The compact constructor makes a defensive, unmodifiable copy. List.copyOf also rejects null elements. Without it, a caller who kept a reference to the original list could change the invoice later.
Other points to keep in mind:
- A variant with no data is still a record, such as
Pending(). TwoPendinginstances are equal by value. If the variants are only constants with no per-variant data, an enum is simpler, and an enum can also implement a sealed interface. - Records cannot extend another class, so a variant cannot inherit state. Share behavior through interface default methods.
- A
switchover anullselector throwsNullPointerException, even when every variant is covered. Usecase nullifnullis a valid input, or validate at the boundary. - If you add a variant later, every switch without a
defaultfails to compile. That failure is the benefit. It lists every place that needs a decision. If the sealed type is in a separately compiled library, code compiled earlier may instead throwMatchExceptionat runtime. Recompile the dependent code when the hierarchy changes.
Checking your model
When you design a sealed hierarchy, ask these questions in order.
- Is the set of alternatives really fixed? If outside code must add its own, use an open interface instead.
- What data does each alternative need? Put exactly those fields in its record.
- Which invariants can a compact constructor enforce, such as non-null values, ranges and defensive copies?
- Which operations will you write as switches, and does each one deserve a
default?
Exercise
You are modeling the result of parsing a command-line argument. It is either Flag(String name), Option(String name, String value), or Invalid(String raw, String reason). Write the sealed interface with nested records and a method String show(Arg arg) that uses a switch with record patterns and no default branch. Then say what happens to the code if you later add a fourth record Positional(String value).
Show answer
sealed interface Arg { record Flag(String name) implements Arg {} record Option(String name, String value) implements Arg {} record Invalid(String raw, String reason) implements Arg {} } and static String show(Arg arg) { return switch (arg) { case Arg.Flag(String n) -> "flag " + n; case Arg.Option(String n, String v) -> "option " + n + "=" + v; case Arg.Invalid(String raw, String reason) -> "invalid " + raw + ": " + reason; }; }. After adding Positional, show no longer compiles because the switch is not exhaustive. The compiler reports the missing case, and you add a case for Positional (or deliberately a default) to fix it.
Exercise
Why is a single class with a status enum and several nullable fields a weaker model than a sealed interface with one record per status?
Show answer
The single class allows illegal combinations, such as a PENDING order with a tracking number or a SHIPPED order with none, and the compiler cannot detect them. With one record per status, each variant has exactly the fields it needs, constructors can enforce them, and a switch over the sealed type is checked for exhaustiveness.