Reputation: 55
I know that using this cloning mechanism is not a good idea (since it is 'broken' as some authors suggest), although I need help understanding how it works. We're given the following class hierarchy:
class N implements Cloneable{
protected int num;
public N clone() throws CloneNotSupportedException{
return (N)super.clone();
}
}
class M extends N{
protected String str;
public M clone() throws CloneNotSupportedException{
M obj = (M)super.clone();
obj.setString(new String(this.str));
return obj;
}
void setString(String str){
this.str = str;
}
}
Since N
extends Object
, how does the super.clone()
return an instance of N
? super.clone()
is actually Object.clone()
which returns a reference to an object of class Object
. Why are we then able to cast it to N
? N
has a member num
that is not in the class Object
. How does the default behavior actually manage to automatically clone this variable (since it has no record of it in class Object
)?
Also, the same goes for M. In M.clone()
we're casting an object from class N
(returned by super.clone()
) to an object of class M
. I know that all of this is valid, yet I do not understand why.
Upvotes: 3
Views: 279
Reputation: 271
You can also use the XStream object to clone your objects, like this :
public static <T> T cloneObject(
T object) {
XStream xstream = new XStream();
return (T) xstream.fromXML(xstream.toXML(object));
}
Upvotes: 0
Reputation: 6131
Answers :
Upvotes: 0
Reputation: 36630
Technically, Object.clone()
is a native method:
protected native Object clone() throws CloneNotSupportedException;
And the JVM internally knows how big the current object is, and what the type of the object is. So, it can create the appropriate object as a bit-wise copy and return a reference to it.
Upvotes: 2
Reputation: 200148
Object#clone
is a native method that makes a low-level binary copy of your object, thus producing another instance of the same class. Therefore it is safe to downcast.
Note that this is the only way to have a polymorphic cloning method.
Upvotes: 6