Records
On This Lesson 4 topics
The content for this lesson is written and waiting for review. The outline below shows what it covers. It will be published once it is approved.
In this lesson
replace a boilerplate data class with a record.
Planned topics
- A record is a short way to write an immutable data class.
- Java generates the constructor, getters (like
name()),equals,hashCode, andtoString. - A compact constructor has no parameter list. Use it to validate the values.
- Records are shallow: if a component is a mutable list, copy it with
List.copyOf. - Records cannot have setters or extra instance fields.
Draft outline details
Demonstration
public record Money(long cents, String currency) {
public Money {
if (cents < 0) throw new IllegalArgumentException("negative");
currency = currency.toUpperCase();
}
}Check your understanding
What does a compact constructor do?
Show answer
It runs checks or cleans values before the fields are set.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.