【发布时间】:2017-11-16 07:16:37
【问题描述】:
在this 问题和post 中解释了如何使用受保护的复制构造函数克隆具有最终字段的对象。
但是,假设我们有:
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)并且它不需要声明@ 987654327@(您可能应该为Brain这样做)。 -
我忍不住停下来想你的问题实际上相当于“我如何克隆一个人?”我们没有人认为这很奇怪,因为我们是程序员。
-
我觉得更多的是设计问题。如果 Person 类的所有可能实现都是未知的,我会问自己在这种情况下使用继承是否正确。可以使用组合来解决问题吗?哪个是 Person 的可能实现?因为如果可以使用组合,解决方法很简单,就是调用Person的构造函数并设置所有变量,否则,如果继承很重要,你知道你需要Person中的
Person clone()方法,所以声明它是抽象的,所有的实现都将决定如何实现它。希望对您有所帮助,干杯!
标签: java abstract-class clone