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.