CKTIS / Java
Records and sealed hierarchies
Records and sealed hierarchies: A record declares a nominal data carrier: components produce private final fields, accessors, a canonical constructor, and value-based equals, hashCode, and toString; a record is implicitly final.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
records sealedA record declares a nominal data carrier: components produce private final fields, accessors, a canonical constructor, and value-based equals, hashCode, and toString; a record is implicitly final.
Combine a sealed interface with record variants to model a closed hierarchy handled by an exhaustive pattern switch.
Record immutability is shallow: a mutable component can still change, and an array component is compared by array identity.
A direct sealed subtype must be permitted and declared final, sealed, or non-sealed; in an unnamed module it must share the package.
The Circle record prints Circle[radius=3], and the exhaustive switch over sealed Shape computes areas 9 and 8.
Examples
sealed interface Shape permits Circle, Rectangle {}
record Circle(int radius) implements Shape {}
record Rectangle(int width, int height) implements Shape {}
public class Main {
static int area(Shape shape) {
return switch (shape) {
case Circle c -> c.radius() * c.radius();
case Rectangle r -> r.width() * r.height();
};
}
public static void main(String[] args) {
Circle circle = new Circle(3);
System.out.println(circle);
System.out.println(area(circle));
System.out.println(area(new Rectangle(2, 4)));
}
}
Result
Circle[radius=3] 9 8
The Circle record prints Circle[radius=3], and the exhaustive switch over sealed Shape computes areas 9 and 8.