如何在Java中克隆具有最终字段的抽象对象?
2022-09-02 21:01:16
在这个问题和这篇文章中,解释了如何使用受保护的复制构造函数克隆具有最终字段的对象。
但是,假设我们有:
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(); //!!!!
…
}
返回错误,因为我们无法实例化抽象类。我们该如何解决这个问题?