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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With