Cloning via clone()

The Object class contains a method named clone(). This method is useful for creating shallow copies (it can be used for deep copies as well). In order to use it, a class should follow the given steps:

  • Implement the Cloneable interface (if this interface is not implemented, then CloneNotSupportedException will be thrown).
  • Override the clone() method (Object.clone() is protected).
  • Call super.clone().

The Cloneable interface doesn't contain any methods. It is just a signal for JVM that this object can be cloned. Once this interface is implemented, the code needs to override the Object.clone() method. This is needed because Object.clone() is protected, and, in order to call it via super, the code needs to override this method. This can be a serious drawback if clone() is added to a child class since all superclasses should define a clone() method in order to avoid the failure of the super.clone() chain invocation.

Moreover, Object.clone() doesn't rely on a constructor invocation, and so the developer cannot control the object construction:

public class Point implements Cloneable {

private double x;
private double y;

public Point() {}

public Point(double x, double y) {
this.x = x;
this.y = y;
}

@Override
public Point clone() throws CloneNotSupportedException {
return (Point) super.clone();
}

// getters and setters
}

Creating a clone can be done as follows:

Point point = new Point(...);
Point clone = point.clone();
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset