A record declares its fields once and gets a constructor, accessors, equals, hashCode and toString for free.
Java · intermediate · 7 min · 25 steps · free
record Point(int x, int y) {
Point { // a compact constructor: checks the values
if (x < 0 || y < 0) throw new IllegalArgumentException("negative");
}
double distanceFromOrigin() {
return Math.sqrt(x * x + y * y);
}
}
public class RecordsDemo {
public static void main(String[] args) {
Point a = new Point(3, 4);
Point b = new Point(3, 4);
int x = a.x(); // accessors are made for you
boolean equal = a.equals(b); // equals compares the values
double d = a.distanceFromOrigin();
System.out.println(a + " " + x + " " + equal + " " + d);
}
}Point { // a compact constructor: checks the values.x in the Point object changes from 0 to 3. y in the Point object changes from 0 to 4.Point() has finished, so its variables are gone.a is created on the stack and points to a new Point on the heap: {x: 3, y: 4}.Point constructor to set up the new object, with x = 3 and y = 4.Point { // a compact constructor: checks the values.if (x < 0 || y < 0) throw new IllegalArgumentException("negative").x in the Point object changes from 0 to 3. y in the Point object changes from 0 to 4.Point() has finished, so its variables are gone.b is created on the stack and points to a new Point on the heap: {x: 3, y: 4}.x() has finished, so its variables are gone.x.equals() has finished, so its variables are gone.equal.distanceFromOrigin() has finished, so its variables are gone.d.toString(). It gets its own variables on the stack.toString() has finished, so its variables are gone.Point[x=3, y=4] 3 true 5.0.Answer: p.y(). Accessors match the field names.
Answer: No. Fields are final.
← var: Local Type Inference · Switch Expressions and Pattern Matching →