Java 16 · Topic 1 of 3
Records
Definition​
A record is a short way to declare a class that only carries data. You list the fields once, and Java creates the constructor, getters, equals, hashCode and toString. The fields are final.
Example code​
A data class in one line
record Point(int x, int y) {
double distanceFromOrigin() { return Math.sqrt(x * x + y * y); } // records can have methods
Point { // compact constructor: validation
if (x < 0 || y < 0) throw new IllegalArgumentException("coordinates must be positive");
}
}
class Demo {
public static void main(String[] args) {
Point p = new Point(3, 4);
System.out.println(p); // toString is generated
System.out.println(p.x() + ", " + p.y()); // accessors are generated
System.out.println(p.equals(new Point(3, 4))); // equals compares the values
System.out.println(p.distanceFromOrigin());
}
}
// Output:
// Point[x=3, y=4]
// 3, 4
// true
// 5.0
Finished this page? Track your progress (saved only in your browser).