i want to clone a given object.
if i do this
public class Something{
Object o; //set in the constructor
public Something(Object o){
this.o = o;}
public Something clone() throws CloneNotSupportedException{
Something temp = super.clone();
if (o instanceof Cloneable) //important part
temp.o = o.clone(); //important part
else temp.o = o;
}
}
this will not work becuase o.clone() is protected.
if i do this instead
if (o instanceof Cloneable) //important part
temp.o = ((Cloneable)o).clone(); //important part
it won't work either because Cloneable is an empty interface.
so how do i convince the compiler that you can clone o?
You can't, when implementing clone() one must know what is cloning, must know the implementation class.
An alternative to cloning is to use copy-constructor, that has the same issue, you must know the class.
Some say do not use clone, others say define your own interface, eg:
Copyablehttp://c2.com/cgi/wiki?CloneableDoesNotImplementClone