Java learning – Immutability with Records – Constructors
Records, in Java, can help to implement immutability due to their inherent properties and restrictions.
Final Fields:
- Fields defined within a record are implicitly
final
. This means that once a record instance is created and its fields are assigned values in the constructor, these values cannot be changed.
- Fields defined within a record are implicitly
Auto-generated Methods:
Records
automatically generates the methodsequals()
,hashCode()
, andtoString()
based on the record fields. These generated methods use all the record’s fields to determine equality, compute hash codes, and provide string representations.
Compact Constructor:
- The
record
constructor assigns values to the fields during object creation. Once these fields are set, they cannot be changed, reinforcing the immutability of the instance.
- The
Here’s an example illustrating how records achieve immutability with a record
:
public record Point(int x, int y) {
// The fields declared in the constructor are final by default
}
With this Point
record, the fields x
and y
are implicitly final. Once a Point
object is instantiated, its x
and y
values cannot be modified:
public static void main(String...args) {
Point origin = new Point(0, 0);
int x = origin.x(); // there is no setX
int y = origin.y();
}
Records provide a concise and safe way to model immutable data types, making code more predictable, easier to reason about, and less prone to unintended side effects or bugs caused by mutable states.
The record itself does not prohibit mutation of the objects it references if those objects are themselves mutable.
public record Line(Point start, Point end) {
}
If the Point type in the constructor is mutable, the Line will be mutable too, since indirectly it will be possible to change the values of the Point, changing to a different line.