Introduction
The java records sealed interfaces combination was finalised across Java 16 and Java 17 between March 2021 and September 2021. Records were finalised by JEP 395 in Java 16 after preview work in Java 14 (JEP 359) and Java 15 (JEP 384); sealed classes and interfaces were finalised by JEP 409 in Java 17 after previews in Java 15 (JEP 360) and Java 16 (JEP 397). Together they enable a style of data modelling that was previously only available in Scala case classes and Kotlin data classes: immutable, transparent data carriers (records) constrained to a closed set of permitted subtypes (sealed), with the compiler enforcing exhaustiveness when you pattern-match over them.
For a Java learner, java records sealed interfaces is the modern replacement for the verbose DTO-and-visitor pattern that dominated Java from 1996 to 2020. A record replaces 80 lines of constructor, getters, equals, hashCode, and toString with a single line; a sealed interface replaces an abstract base class with a compile-time-checked closed set of permitted implementations; and pattern matching (JEP 394 for instanceof in Java 16, JEP 406 and JEP 441 for switch in Java 17 and Java 21) replaces the runtime-checked visitor pattern with a compile-time-checked type switch. Interviewers love asking about records because the feature looks trivial on the surface but has deep interactions with the JLS, the JVM, and the type system.
What is Java Records Sealed Interfaces?
Java records sealed interfaces is the combination of two Java language features: the record keyword that declares an immutable transparent data carrier, and the sealed keyword that declares a class or interface whose direct subtypes are restricted to a known permit list. A record is final and cannot be extended; it has an implicit canonical constructor that takes every component as a parameter, implicit accessor methods named after each component (not getXxx), and implicit equals, hashCode, and toString implementations that follow the contract. A sealed interface declares permits Sub1, Sub2, Sub3 and the compiler rejects any direct implementation or extension outside that list.
Java records sealed interfaces belongs to the data modelling category of language features. A record is different from a regular class because it is final and immutable and its components are exposed directly; a sealed interface is different from a regular interface because only the permits list may implement or extend it. Together they model algebraic data types: the sealed interface is a sum type (one of these permitted implementations) and a record is a product type (every component is logically ANDed). The compiler can prove exhaustiveness of a switch over a sealed hierarchy because every direct subtype is known at compile time.
How Java Records Sealed Interfaces Works - Step by Step
Step 1: Record declaration. The developer writes record Point(int x, int y) {}. The compiler generates a final class that extends java.lang.Record (the abstract base class added in Java 16, JEP 395), with two private final fields x and y, a canonical constructor Point(int x, int y), accessor methods x() and y(), and equals, hashCode, and toString implementations that use every component. The bytecode for these methods is generated by the compiler, not the JIT, and is identical to what you would write by hand.
Step 2: Compact constructor. If the record needs to validate its arguments, the developer writes a compact constructor with no parameter list and no formal parameters, which the compiler expands into the canonical constructor's body. For example, record Range(int lo, int hi) { public Range { if (lo > hi) throw new IllegalArgumentException(); } }. The implicit assignment this.lo = lo; this.hi = hi; happens at the end of the compact constructor, after the validation, so the record is never seen in an invalid state.
Step 3: Sealed interface declaration. The developer writes sealed interface Shape permits Circle, Square, Triangle {}. The compiler records the permits list in the class file's PermittedSubclasses attribute (added in Java 17). Every direct implementation or extension must be in the permits list, must be in the same module or package, and must itself be either final, sealed, or non-sealed (the new keyword added in Java 17 to mark a subtype that opens the hierarchy back up).
Step 4: Record implements sealed. The developer writes record Circle(double radius) implements Shape {}. Because a record is implicitly final, it satisfies the sealed interface's requirement that every permitted subtype be either final, sealed, or non-sealed. The compiler records the implementation relationship in the bytecode, and the runtime's reflection API can recover the permits list via Class.getPermittedSubclasses() (added in Java 17).
Step 5: Pattern matching exhaustiveness. The developer writes a switch expression over the Shape interface, with a case for Circle, Square, and Triangle. Because the compiler knows the permits list, it can prove the switch is exhaustive without a default branch; if a new subtype is added to the permits list, the compiler emits an error at every switch that no longer covers the new case. This is the key safety property of java records sealed interfaces: adding a new variant causes a compile error in every switch, which is the type-system equivalent of refactoring support.
Java Program for Java Records Sealed Interfaces
import java.util.Objects;
// Sealed interface: only Circle, Square, Triangle may implement
sealed interface Shape permits Circle, Square, Triangle {
double area();
}
// Records implementing the sealed interface
record Circle(double radius) implements Shape {
public Circle {
if (radius < 0) {
throw new IllegalArgumentException("radius must be non-negative");
}
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
record Square(double side) implements Shape {
@Override
public double area() {
return side * side;
}
}
record Triangle(double base, double height) implements Shape {
@Override
public double area() {
return 0.5 * base * height;
}
}
public class RecordsSealedDemo {
// Pattern matching for switch (JEP 441, Java 21 final,
// preview in Java 17 as JEP 406). Exhaustive over the sealed
// hierarchy, no default branch needed.
static String describe(Shape s) {
return switch (s) {
case Circle c -> "circle radius " + c.radius();
case Square sq -> "square side " + sq.side();
case Triangle t -> "triangle " + t.base() + "x" + t.height();
};
}
// Pattern matching for instanceof (JEP 394, Java 16)
static double areaOf(Object o) {
if (o instanceof Circle c) {
return c.area();
} else if (o instanceof Square sq) {
return sq.area();
} else if (o instanceof Triangle t) {
return t.area();
}
throw new IllegalArgumentException("unknown shape: " + o);
}
public static void main(String[] args) {
Shape[] shapes = {
new Circle(2.0),
new Square(3.0),
new Triangle(4.0, 5.0)
};
for (Shape s : shapes) {
System.out.println(describe(s) + " area = " + s.area());
}
// Equality, hashCode, toString are auto-generated
Circle c1 = new Circle(2.0);
Circle c2 = new Circle(2.0);
System.out.println();
System.out.println("c1.equals(c2): " + c1.equals(c2));
System.out.println("c1.hashCode() == c2.hashCode(): "
+ (c1.hashCode() == c2.hashCode()));
System.out.println("c1.toString(): " + c1);
System.out.println("c1.radius():>0: " + (c1.radius() > 0));
// Pattern matching for instanceof on an Object
System.out.println();
System.out.println("area of Square(3): " + areaOf(new Square(3.0)));
// Compact constructor validation
try {
Circle bad = new Circle(-1.0);
System.out.println("Should not reach: " + bad);
} catch (IllegalArgumentException e) {
System.out.println("Caught: " + e.getMessage());
}
// Reflection access to the permits list (Java 17+)
System.out.println();
System.out.println("Permitted subtypes of Shape:");
for (Class<?> c : Shape.class.getPermittedSubclasses()) {
System.out.println(" " + c.getSimpleName());
}
}
}
Code Explanation - Line by Line
The sealed interface Shape permits Circle, Square, Triangle declares a closed hierarchy. The permits clause lists every direct implementation that the compiler will allow; any other class or record that tries to write implements Shape is rejected at compile time. The permits list is stored in the PermittedSubclasses class file attribute (added in Java 17) so that the runtime reflection API can recover it via Class.getPermittedSubclasses().
The three records Circle, Square, and Triangle all implement Shape and are implicitly final (records are always final). Because they are final, they satisfy the sealed interface's rule that every permitted subtype be final, sealed, or non-sealed. The Circle record demonstrates the compact constructor: the body if (radius < 0) throw new IllegalArgumentException(...) validates the radius, and the implicit assignment this.radius = radius happens at the end of the compact constructor, after the validation, so the record can never be observed with a negative radius.
The describe(Shape) method uses pattern matching for switch (JEP 406 preview in Java 17, finalised in JEP 441 in Java 21). The switch expression covers the three permitted subtypes and the compiler can prove exhaustiveness because the permits list is closed. If a new subtype Rectangle is added to the permits list, every switch like this one will fail to compile until a case for Rectangle is added -- which is the type-system refactor support that sealed interfaces exist to provide. The arrow syntax case Circle c -> ... binds the cast value to the variable c, which is in scope in the right-hand-side expression.
The areaOf(Object) method uses pattern matching for instanceof (JEP 394, finalised in Java 16). The pattern o instanceof Circle c combines the type check and the binding in a single expression, so the rest of the if block can use c without an explicit cast. The pattern variable c is in scope only where the pattern definitely matched, which the compiler proves by flow analysis. The default throw is necessary because Object is not a sealed type and the compiler cannot prove the chain is exhaustive.
The main method demonstrates equality, hashCode, and toString, which are auto-generated by the record's compiler. Two Circle(2.0) instances are equal because every component is equal, their hashCodes are equal (because the contract requires equal objects to have equal hashCodes), and the toString output is Circle[radius=2.0] in the canonical record format. The accessor c1.radius() returns the component value directly; records do not use the getRadius() Java-Beans naming convention because records are not Java-Beans, they are transparent data carriers.
The getPermittedSubclasses() reflection call returns the array of classes listed in the permits clause. This is the runtime equivalent of the compile-time check: any tool that needs to know all permitted subtypes (JSON serializers, ORM mappers, IDE quick-fixes) can discover them at runtime. The output prints Circle, Square, and Triangle as the three permitted subtypes.
Interview Questions and Answers
Q1. What is a Java record and what does the compiler generate for you?
A record is a final, immutable data carrier class declared with the record keyword, finalised in Java 16 by JEP 395. For each record record Point(int x, int y) {}, the compiler generates a private final field per component, a canonical constructor that takes every component, an accessor method per component (named after the component, not getXxx), and equals, hashCode, and toString implementations that use every component. The record extends java.lang.Record, the abstract base class added in Java 16 to let reflection identify record classes.
Q2. What is a sealed interface or sealed class, and what problem does it solve?
A sealed class or interface (JEP 409, finalised in Java 17) restricts its direct subtypes to a permit list declared with the permits clause. Every permitted subtype must be in the same module or package and must itself be final, sealed, or non-sealed. The problem it solves is the loss of exhaustiveness: with a regular interface, anyone can write implements Shape, so the compiler cannot prove a switch over Shape is exhaustive and forces a default branch. With a sealed interface, the permits list is closed and the compiler can prove exhaustiveness, so adding a new subtype causes a compile error at every switch.
Q3. What is a compact constructor and when is it used?
A compact constructor is a record constructor with no formal parameter list and no explicit field assignments, written as public Range { if (lo > hi) throw ...; }. The compiler expands it into the canonical constructor, with the implicit assignments this.lo = lo; this.hi = hi inserted at the end of the body. The compact constructor is used to validate arguments or normalise them (cloning defensive arrays, clamping values) before the implicit assignment runs, so the record can never be observed in an invalid state. Without the compact constructor, the implicit canonical constructor simply assigns each parameter to the corresponding field.
Q4. How do records interact with equals, hashCode, and toString?
The compiler-generated equals returns true only if the other object is the same record class and every component is equal. The compiler-generated hashCode is the same as Objects.hash(components) -- it uses every component. The compiler-generated toString uses the format RecordName[comp1=val1, comp2=val2]. All three follow the contract: equal records have equal hashCodes, and toString is a valid Java expression for a record. You can override any of these methods by writing your own, but the contract (equal objects must have equal hashCodes) must still be satisfied.
Q5. What is pattern matching for instanceof, and what does the pattern variable do?
Pattern matching for instanceof (JEP 394, finalised in Java 16) combines a type check with a binding. The expression if (o instanceof Circle c) { ... } checks whether o is an instance of Circle, and if so, binds the cast value to a fresh variable c. The variable c is in scope only where the pattern definitely matched (the then-branch of the if, the right side of a short-circuit &&), which the compiler proves by flow analysis. The pattern eliminates the verbose Circle c = (Circle) o cast that was standard before Java 16.
Q6. How does pattern matching for switch work with sealed hierarchies?
Pattern matching for switch (JEP 406 preview in Java 17, JEP 441 final in Java 21) introduces type patterns like case Circle c -> and guard patterns like case Circle c && c.radius() > 10 ->. With a sealed hierarchy, the compiler uses the permits list to prove exhaustiveness, so no default branch is required. If a new subtype is added to the permits list, every switch expression over the hierarchy fails to compile until a case for the new subtype is added. The arrow form -> returns the right-hand-side value, so the switch is an expression not a statement.
Q7. Senior scenario: you are migrating a class hierarchy with 50 subtypes and 200 visitors to Java 17 sealed classes and pattern matching. What are the trade-offs?
The trade-off is between exhaustiveness safety and binary compatibility. Sealing the hierarchy means that adding a 51st subtype breaks compilation of every switch, which is the safety property you want, but it also means that downstream code that uses your library cannot add a new subtype without you re-releasing the library. If the library is shipped as a JAR and the downstream project adds its own subtype (which is now forbidden), the binary compatibility story is broken. The standard practice is to ship sealed hierarchies only within a single module or a single team, and to ship non-sealed hierarchies as the public API. The visitor pattern remains the right choice when the operation set is small and stable but the subtype set is open.
Sample Input and Output
Input: java RecordsSealedDemo Output: circle radius 2.0 area = 12.566370614359172 square side 3.0 area = 9.0 triangle 4.0x5.0 area = 10.0 c1.equals(c2): true c1.hashCode() == c2.hashCode(): true c1.toString(): Circle[radius=2.0] c1.radius()>0: true area of Square(3): 9.0 Caught: radius must be non-negative Permitted subtypes of Shape: Circle Square Triangle
The output confirms the four behaviours: the pattern-matching switch dispatched to the correct case for each Shape subtype, the auto-generated equals returns true for two equal Circle records, the auto-generated hashCode is consistent, the auto-generated toString uses the canonical record format, the compact constructor rejected a negative radius, and the reflection API reported the three permitted subtypes.
Common Mistakes to Avoid
First, writing getters with the Java-Beans naming convention. Records use accessor methods named after the component, so record Point(int x, int y) exposes x() and y(), not getX() and getY(). Mixing the two conventions breaks JSON serializers that introspect for getters, so pick one convention per class and stick with it.
Second, declaring a record mutable. A record's components are implicitly final, and the accessor methods are not setters, so a record is immutable by construction. If you try to add a setter, the compiler rejects it. If you find yourself wanting a mutable record, you almost certainly want a regular class instead.
Third, sealing a public library hierarchy. Sealed hierarchies break binary compatibility because every new permitted subtype requires recompiling every switch. Ship sealed hierarchies only within a single module or a single team. For a public library, prefer non-sealed or a regular interface.
Fourth, forgetting that the permits list must list every direct subtype. If you write sealed interface Shape permits Circle and then add record Square implements Shape, the compiler rejects Square. The permits list is exhaustive and must be updated whenever a new direct subtype is added.
Real-World Applications
The java records sealed interfaces combination is the standard modern Java idiom for data modelling in the JDK itself and in every framework that has migrated to Java 17 or later. The JDK uses records for java.lang.foreign.MemorySegment, java.lang.Runtime.Version, and the new HTTP client API's HttpRequest and HttpResponse. Spring Framework 6 (November 2022) uses records for configuration properties, request bodies, and Spring Bean definitions. Spring Boot 3 supports records as configuration classes and as @ConfigurationProperties.
Reactive libraries Reactor and RxJava use records for their event and signal types. Quarkus and Helidon use records for configuration and bean metadata. JPA and Hibernate 6 support records as @Embeddable and as projection types in repository queries. JSON-B (the standard JSON binding API) and Jackson support records as serialisable types. The combination of records with sealed interfaces and pattern matching is the basis of the modern Java data-modelling story, and it is what makes Java 17 a meaningfully different language from Java 8.
Conclusion
Java records sealed interfaces is the modern data-modelling idiom: records replace the verbose DTO-and-getters boilerplate, sealed interfaces replace the open-and-uncheckable abstract base class, and pattern matching over the sealed hierarchy replaces the runtime-checked visitor pattern with a compile-time-checked type switch. We walked through the compact constructor, the permits list, the pattern-matching switch exhaustiveness, and the reflection API. To go deeper, study JEP 395 (records), JEP 409 (sealed classes), JEP 394 (pattern matching for instanceof), and JEP 441 (pattern matching for switch), then read the OpenJDK source for java.lang.Record and the PermittedSubclasses attribute.
Comments
Comments
Post a Comment