When searching the net for possibilities how to make a deep copy of an object polymorphically, I found a solution that claims to solve many issues with the clone()
method, e.g. the impossibility to clone final
fields. The solution combines the use of a protected copy constructor inside the clone()
implementation and basically goes like this (example copied from the referenced page):
public class Person implements Cloneable
{
private final Brain brain; // brain is final since I do not want
// any transplant on it once created!
private int age;
public Person(Brain aBrain, int theAge)
{
brain = aBrain;
age = theAge;
}
protected Person(Person another)
{
Brain refBrain = null;
try
{
refBrain = (Brain) another.brain.clone();
// You can set the brain in the constructor
}
catch(CloneNotSupportedException e) {}
brain = refBrain;
age = another.age;
}
public Object clone()
{
return new Person(this);
}
…
}
The clone()
method of Brain
may be implemented in a similar way.
Based on the documentation of the clone()
method, it seems that all "contracts" of this method 'are not absolute requirements' and that 'the returned object should be obtained by calling super.clone()
' is just a convention.
So, is this implementation actually incorrect? Why?
And if it is correct, why it did not become a design pattern? What are the downsides of this???
Thanks, Petr