
🎬 Java Record Classes
Featuring Famous French Actors
In Java, record classes offer a concise, readable way to define immutable data structures—like casting actors for roles with a fixed script: no improvisation allowed!
🧑🎤 Record Classes Are Final (Like Legendary Performances)
Record classes are implicitly final. That means:
🟣 You can’t extend them.
🟣 But they can be generic, implement interfaces, and be annotated just like normal classes.
Let’s explore these features using a cinematic theme.
🌟 Example 1: A Generic Record – AwardedActor
We want to record information about an actor and their Oscar prize. We'll make it generic to support different date formats.
Here, Marion Cotillard won her Oscar in 2008 for La Vie en Rose.
We use generics to support different types of dates (LocalDate, ZonedDateTime, etc.).🎞️ Example 2: A Record Implementing an Interface – Actor implements Star
We define a Star interface for anyone who shines on screen:
Now let’s implement this in a record:
Even though records are compact, they can still carry behavior.
🕰️ Example 3: Annotated Record – Movie
We want to ensure our movies have a valid duration and a proper release date. Let's define a custom annotation:
Now let's define the Movie record:
What Does This Translate To Behind the Scenes?
This annotated record:
Is roughly equivalent to this normal class:
➡️ The annotations apply to the fields thanks to @Target(ElementType.FIELD).
🎯 Recap – Records with a Touch of Glamour