...
When the values of the x and y members must remain immutable after their initialization, they should be declared final. However, this invalidates a set_xy() method because it can no longer change the values of x and y.:
| Code Block | ||
|---|---|---|
| ||
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
}
|
...
If the class must remain mutable, another compliant solution is to provide copy functionality. This compliant solution provides a clone() method in the class Point, avoiding the elimination of the setter method.:
| Code Block | ||
|---|---|---|
| ||
final public class Point implements Cloneable {
private int x;
private int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
void set_xy(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);
}
public Point clone() throws CloneNotSupportedException{
Point cloned = (Point) super.clone();
// No need to clone x and y as they are primitives
return cloned;
}
}
public class PointCaller {
public static void main(String[] args) throws CloneNotSupportedException {
Point point = new Point(1, 2); // willWill not be changed in main()
point.print_xy();
// Get the copy of original object
Point pointCopy = point.clone();
// pointCopy now holds a unique reference to the newly cloned Point instance
// Change the value of x,y of the copy.
pointCopy.set_xy(5, 6);
// Original value remains unchanged
point.print_xy();
}
}
|
...
This compliant solution declares a private array from which a public immutable list is constructed.:
| Code Block | ||
|---|---|---|
| ||
private static final String[] items = { ... };
public static final List<String> itemsList =
Collections.unmodifiableList(Arrays.asList(items));
|
...