I need to equip my class with polymorphic cloning (deep copy), i.e. I need something like this to work:
SuperType original = new SubType();
SuperType copy = original.clone();
where original.clone()
can be substituted by any mechanism to create a deep copy, and the actual type of copy
shall be SubType
, because original
is also a SubType
.
Is the clone()
method and Cloneable
interface the only way to achieve this? Factory methods and copy constructors cannot by used, since the actual class is known only in run time, right? Are there any other suggested methods except those serialize-deserialize approaches, and the Java deep-cloning library which is IMHO even worse black magic than the clone()
method?
Thanks, Petr
Clone() method in Java. Object cloning refers to the creation of an exact copy of an object. It creates a new instance of the class of the current object and initializes all its fields with exactly the contents of the corresponding fields of this object. In Java, there is no operator to create a copy of an object.
There are two types of object cloning - shallow cloning, and deep cloning. Let's understand each of them and find out the best way to implement cloning in our Java programs.
The clone() method isn't defined by the Cloneable interface. The clone method in the Object class is protected to prevent a client class from calling it - Only subclasses can call or override clone, and doing so is a bad idea.
The clone() method of Object class is used to clone an object. The java. lang. Cloneable interface must be implemented by the class whose object clone we want to create.
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:
Joshua Block's opinion on cloning vs. copy constructor
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