Actually Object's clone()
method is not allowing you to do any polymorphic calling because is protected
. Implementing Cloneable
is of no use either because it doesn't contain a clone()
method.
You can do polymorphic cloning by providing a polymorphic method for the cloned classes that in turn invoke the copy constructor.
abstract class SuperType {
public SuperType(SuperType t) {
}
public abstract SuperType deepCopy();
}
class SomeType extends SuperType {
SomeType(SomeType t) {
//copy constructor
}
@Override
public SomeType deepCopy() {
return new SomeType(this);
}
}
...
SuperType original = new SubType();
SuperType copy = original.deepCopy(); //the deepCopy is called on children classes
See also: