gpt4 book ai didi

java - 如何在 Java 中克隆具有最终字段的抽象对象?

转载 作者:太空狗 更新时间:2023-10-29 22:52:16 26 4
gpt4 key购买 nike

this问题和这个post解释了如何使用 protected 复制构造函数克隆具有最终字段的对象。

但是,假设我们有:

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()方法,只在具体的子类中实现。

public class SomeConcretePerson extends Person
{
public SomeConcretePerson (SomeConcretePerson another)
{
super (another); // this will invoke Person's copy constructor
}

public Object clone()
{
return new SomeConcretePerson(this);
}
}

关于java - 如何在 Java 中克隆具有最终字段的抽象对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44539645/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com