Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 441
Arijit Dasgupta Avatar asked Sep 27 '22 12:09

Arijit Dasgupta


2 Answers

Implementing the Cloneable interface is needed in order for a call to Object.clone() to not throw an exception. (That's the entire purpose of Cloneable.)

You are not using Object.clone(). So implementing Cloneable or not has no effect. It has nothing to do with what your method is called. Your method could be called testClone() and it can call up to super.clone(). Or your method could be called clone() and it could not use super.clone(). What matters is you are not using Object.clone().

The advantage of using Object.clone() is that the object it returns has the same exact runtime class as the object it is called on. On the other hand, your method creates a new ColoredCircle object always. So when your testClone() method is inherited in a subclass, it will still create a ColoredCircle, and not an instance of that subclass. Whereas if your method called super.clone() it will be able to get an instance of whatever subclass the current instance is.

like image 163
newacct Avatar answered Sep 29 '22 16:09

newacct


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.

like image 21
Kumar Abhinav Avatar answered Sep 29 '22 17:09

Kumar Abhinav