QuickDevGuide

Home › Java

Records, Sealed Classes & Pattern Matching — Java

Modern Java (16–21) adds features for modelling data concisely and safely. Records (Java 16) record Point(int x, int y) {} generates a constructor, accessors (x()), equals, hashCode and toString. Records are immutable and final. Add validation in a compact constructor. Sealed classes (Java 17) sealed interface Shape permits Circle, Square lists every allowed subtype. The compiler then knows the hierarchy is closed — enabling exhaustive switch without a default. Pattern matching (Java 21) instanceof patterns: if (obj instanceof String s) Switch patterns with guards: case Circle c when c.radius() > 10 -> Record patterns destructure: case Point(int x, int y) -> Together these give Java algebraic data types similar to Kotlin's sealed classes or TypeScript discriminated unions.

Key Takeaways