在这个问题和这个帖子中,解释了如何通过使用受保护的复制构造函数克隆具有最终字段的对象。
然而,假设我们有:
public abstract 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 String toString()
{
return "This is person with " + brain;
// Not meant to sound rude as it reads!
}
public Object clone()
{
return new Person(this);
}
public abstract void Think(); //!!!!
…
}
由于我们无法实例化抽象类,因此会返回错误。我们该如何解决这个问题?
clone
时,不要忘记你可以使返回类型更具体(例如Person
而不是Object
),并且它不需要声明throws CloneNotSupportedException
(你可能应该为Brain
这样做)。 - maaartinusPerson clone()
方法,所以将其声明为抽象的,所有的实现都将决定如何实现它。希望能帮到你,加油! - rascio