Search code examples
javainterfaceclonecloningcloneable

Why do we implement Cloneable even if we can go for deep cloning using the following snippet


public class Color {
 String color;
 Color(String color)
 {
   this.color=color;         
 }
 }


public class ColoredCircle {
int x;
Color color;
ColoredCircle(int x, Color color)
{
    this.x=x;
    this.color=color;
}
public Object testClone()
{
    Color c = new Color(this.color.color);
    ColoredCircle cc1 = new ColoredCircle(this.x, c);
    return cc1;
}
}

In the class ColoredCircle mentioned above we have a method named testClone() and it works exactly as Deep Cloning. Now I am confused about the fact that is it necessary to implement Cloneable to clone? And Is the above program a kind of Deep cloning?


Solution

  • Is it necessary to implement Cloneable to clone? Yes.The clone() method is having protected access modifier with the following Javadoc explantion :-

    This method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a shallow copy of this object, not a deep copy operation.

    Your method testClone although may be correct in cloning behavior but is not a Cloneable Object in itself.A Cloneable object must implement Cloneable interface and preferably have a public access for clone() so that it can be used outside the class.

    Someone reaading your class will have a hard time understanding the importance of testClone() method.