Records (preview): Why aren't accessor methods generated as final?
Remi Forax
forax at univ-mlv.fr
Fri Apr 24 21:53:06 UTC 2020
You are asking why accessors can be user defined ?
It's because you may do something useful in an accessor like a defensive copy (cloning of mutable objects at the boundaries of the class).
By example,
class Point { // a mutable class
int x, y;
...
}
record Circle(Point center) {
Circle {
center = new Point(center.x, center.y); // defensive copy
}
public Point center() {
return new Point(center.x, center.y); // defensive copy, too
}
}
There are other examples like normalization/de-normalization/interning, the returned value should be always between [-pi/2,pi/2], the return value is the cached value not a free instance, cases where semantically it makes sense to change the retuned value to an equivalent value.
regards,
Rémi
* you can declare a suer defined @Override, but it's more because the annotation already exists.
----- Mail original -----
> De: "Mike Bishop" <tend2dv8 at gmail.com>
> À: "amber-dev" <amber-dev at openjdk.java.net>
> Envoyé: Vendredi 24 Avril 2020 23:04:23
> Objet: Records (preview): Why aren't accessor methods generated as final?
> I'm curious as to why the accessor methods in a record are not final.
> Consider the following record declaration:
>
> public record Point(double x, double y) {}
>
> The accessor methods x() and y() return x and y, respectively, but are not
> final. This allows me to override x(), for example, as follows:
>
> public record Point(double x, double y) {
> public double x() {
> return x * x;
> }
> }
>
> I can test the above Point record with the following code to ensure that
> two Points with the same declared x and y coordinates are equal.
>
> public static void main(String[] args) {
> var p = new Point(3.0, 4.0);
> var pPrime = new Point(p.x(), p.y());
> System.out.println("p = " + p + ", pPrime = " + pPrime);
> assert pPrime.equals(p);
> }
>
> As expected, the assertion fails as pPrime is (9.0, 4.0) while p is (3.0,
> 4.0).
>
> My concern is that if I'm using a Point in my code, I would expect that two
> Points with the same x and y will be equivalent since the 2-tuple (x, y)
> represents "the state, the whole state and nothing but the state" of Point.
> I think this can only be assured if the accessor methods are final.
>
> Best regards,
> Mike Bishop
More information about the amber-dev
mailing list