library
intermediateRecords (Java 14+)
Use records for immutable data carriers with auto-generated equals, hashCode, toString, and accessors.
Records (preview in Java 14, stable in Java 16) are a concise way to declare immutable data-carrying classes. A record declaration automatically generates: a constructor, accessor methods (not getters — no 'get' prefix), equals(), hashCode(), and toString().
Record = a pre-printed form with labeled fields. You fill in the values once (constructor) and they're locked. The form knows how to compare itself with other forms and describe itself.
Key Concepts
1
class Point { int x; int y; ... } becomes record Point(int x, int y) { }
2
What records provide:
- Final fields for each component (immutable by default)
- Canonical constructor (all components as parameters)
- Accessor methods: point.x() not point.getX()
- equals: component-wise equality
- hashCode: based on all components
- toString: Point[x=1, y=2]
3
What you can customize:
- Compact constructor: validate/normalize without repeating assignments
- Custom methods: add business logic
- Implement interfaces
- Override accessor methods (rare)
4
What records cannot do:
- Extend other classes (they implicitly extend java.lang.Record)
- Be extended (implicitly final)
- Have mutable instance fields (all fields are final)
- Declare instance fields outside the component list
5
Records are ideal for DTOs, value objects, compound map keys, and method return types when you need to return multiple values.