Java Reference
In-Depth Information
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); // Is not 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();
}
}
Search WWH ::




Custom Search