Java 21 record patterns pull components straight out of the object, so there is no cast and no chain of accessor calls.
sealed interface Shape permits Circle, Rect {}
record Circle(double r) implements Shape {}
record Rect(double w, double h) implements Shape {}
List<Shape> shapes = List.of(new Circle(2), new Rect(3, 4));
for (Shape s : shapes) {
String desc = switch (s) {
case Circle(double r) -> "circle area = " + String.format("%.2f", Math.PI * r * r);
case Rect(double w, double h) -> "rect area = " + (w * h);
};
System.out.println(desc);
}
circle area = 12.57
rect area = 12.0
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-07-30