Lab 07: Java 21 — Records, Sealed, Pattern Matching

Objective

Master Java 21's three biggest language features: records (immutable data carriers with compact constructors), sealed interfaces (restricted class hierarchies), and pattern matching switch (exhaustive, type-safe dispatch).

Background

Java 21 (LTS) finalised several major language improvements. Records eliminate boilerplate for data classes — the compiler auto-generates equals, hashCode, toString, and accessors. Sealed interfaces let you define closed hierarchies where the compiler knows every subtype, enabling exhaustive pattern matching. Together they bring algebraic data types to Java.

Time

30 minutes

Prerequisites

  • Lab 06 (File I/O)

Tools

  • Docker: zchencow/innozverse-java:latest


Lab Instructions

Steps 1–8: Records, sealed interface, pattern switch, guarded patterns, text blocks, instanceof, Capstone

💡 Sealed interface + pattern switch = exhaustive dispatch. When all case branches are listed for a sealed type, the compiler proves the switch is exhaustive — no default needed, and no runtime MatchException. Add a new permitted subtype and the compiler instantly flags every switch that's incomplete. This is the Java equivalent of Rust's match or Haskell's ADTs.

📸 Verified Output:


Summary

Feature
Java Version
Key benefit

Records

16 (final)

Auto equals/hashCode/toString, immutable

Compact constructor

16

Validation in records without boilerplate

Sealed classes/interfaces

17 (final)

Closed hierarchies, exhaustive switching

Pattern matching instanceof

16 (final)

Combine type check + cast in one step

Pattern matching switch

21 (final)

Exhaustive type dispatch with guards

Text blocks

15 (final)

Multi-line string literals

Further Reading

Last updated