Sub topic 3
Modeling Data Variants with Sealed Interfaces and Records
Assume you know Java inheritance, records, generics, and switch expressions. Java 17 introduced sealed types. Java 21 adds pattern matching for switch and record patterns.
Sealed interfaces and records
A sealed interface defines a closed set of permitted implementations. Records work well as variants because they are concise and immutable by default.
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 {}Each record is implicitly final, so it cannot create another subtype. A sealed hierarchy makes the possible data shapes explicit:
Sealed types with generics
Sealed types can have type parameters. The permitted classes usually repeat those parameters.
sealed interface Result<T> permits Ok, Error {}
record Ok<T>(T value) implements Result<T> {}
record Error<T>(String message) implements Result<T> {}Result<Integer> can therefore contain either an integer value or an error message. The permitted subtype list is about class structure, not about one particular type argument.
Restrictions
Every direct permitted subtype must choose one of these modifiers:
final, which ends that branch.sealed, which declares another restricted level.non-sealed, which reopens that branch for unrestricted inheritance.
Permitted subtypes must be in the same package, or in the same named module when modules are involved. A class cannot extend a sealed type unless the sealed type explicitly permits it. A permitted class must directly extend or implement the sealed type.
Reflection
Java exposes the hierarchy at runtime:
boolean closed = Shape.class.isSealed();
for (Class<?> subtype : Shape.class.getPermittedSubclasses()) {
System.out.println(subtype.getSimpleName());
}This can help frameworks, serializers, and tests discover supported variants.
Evolving the hierarchy
Adding a permitted subtype changes the contract. Existing pattern-matching switches may become incomplete when recompiled. Add a case for the new subtype and recompile clients that depend on the hierarchy. Treat the permitted list as part of your public API.
Choosing a type design
| Choice | Best fit |
|---|---|
| Sealed interface | A fixed set of data variants with different fields |
| Enum | A fixed set of names with the same basic representation |
| Abstract class | Shared implementation with controlled or open extension |
| Open interface | An extension point for code outside your control |
Exercise
Why is non-sealed a deliberate design choice in a sealed hierarchy?
Show answer
It reopens one branch so classes outside the listed immediate subtypes can extend that branch.