...
If the class must remain mutable, another compliant solution is to provide copy functionality. This compliant solution provides a clone()
method in the final
class 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 { final Point point = new Point(1, 2); // will 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(); } } |
...