Java Reference
In-Depth Information
// Change the value of x, y
point.set_xy(5, 6);
point.print_xy();
}
}
Compliant Solution (
final
Fields)
When the values of the
x
and
y
instance variables must remain immutable after their ini-
tialization, they should be declared
final
. However, this invalidates the
set_xy()
meth-
od because it can no longer change the values of
x
and
y
:
class Point {
private final int x;
private final int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
void print_xy() {
System.out.println("the value x is: " + this.x);
System.out.println("the value y is: " + this.y);
}
// set_xy(int x, int y) no longer possible
With this modification, the values of the instance variables become immutable and
consequently match the programmer's intended usage model.
Compliant Solution (Provide Copy Functionality)
If the class must remain mutable, another compliant solution is to provide copy function-
ality.Thiscompliant solutionprovidesa
clone()
methodintheclass
Point
,avoidingthe
elimination of the setter method: