Lab 13: Records & Sealed Classes Deep Dive

Objective

Master Java 21 records beyond the basics: custom compact constructors, withXxx wither pattern, generic records, canonical constructor delegation, records in streams/maps, and sealed interface hierarchies for algebraic data type patterns with exhaustive pattern matching.

Background

Records (JEP 395) are transparent data carriers — the compiler generates equals, hashCode, toString, and accessors from the component list. Sealed classes (JEP 409) restrict which classes can extend an interface or class — enabling the compiler to prove switch expressions are exhaustive. Combined, they bring algebraic data types (ADTs) to Java.

Time

25 minutes

Prerequisites

  • Practitioner Lab 07 (Java 21 Features)

Tools

  • Docker: zchencow/innozverse-java:latest


Lab Instructions

Steps 1–8: Compact constructor, withers, generic records, records in collections, sealed ADTs, pattern dispatch, deconstruction, Capstone

💡 Record deconstruction patterns (case Created(var id, var prod, var total)) are Java 21's most powerful feature for ADTs. Instead of casting and calling accessors, the switch expression directly binds the components to local variables. This is equivalent to Haskell pattern matching or Rust's match with struct destructuring — finally available in Java.

📸 Verified Output:


Summary

Feature
Notes

Compact constructor

Runs before field assignment; validates/normalises

Wither pattern

withX(val) returns new record, old is unchanged

Generic record

record Pair<A,B>(A first, B second)

sealed interface

Only listed permits can implement

Record deconstruction

case MyRecord(var x, var y) in switch

Result<T>

Functional error handling without exceptions

Further Reading

Last updated