我有一个名为 AClass
的抽象类。在同一个包中,我有 AnotherClass
,其中我有一个 AClass
对象的 ArrayList
。在 AnotherClass
的复制构造函数中,我需要在 ArrayList
中复制 AClass
对象。
问题:
我无法在 AClass
中创建复制构造函数,因为它是一个抽象类,而且我不知道将由 AClass
继承的类的名称。实际上,在这个项目中,没有对象会继承这个类,但这个项目将被其他项目用作库,这些项目将提供 AClass
的子类。是我的设计有问题还是有解决办法?
编辑:这里是一些代码:
public class AnotherClass{
private ArrayList<AClass> list;
...
/** Copy constructor
*/
public AnotherClass(AnotherClass another){
// copy all fields from "another"
this.list = new ArrayList<AClass>();
for(int i = 0; i < another.list.size(); i++){
// Option 1: this.list.add(new AClass(another.list.get(i)));
// problem: cannot instantiate AClass as it is abstract
// Option 2: this.list.add(another.list.get(i).someKindOfClone());
// problem? I'm thinking about it, seems to be what dasblinkenlight is suggesting below
}
}
...
}
最佳答案
I cannot create a copy constructor in
AClass
because it is an abstract class and I cannot know the name of the class which will inherit byAClass
这通常是正确的。然而,由于您有一个 AClass
列表,您不需要知道确切的子类型:一个创建副本的抽象函数就足够了:
protected abstract AClass makeCopy();
这类似于java.lang.Object
的clone()
函数,只是所有的子类都必须实现它,并且要求返回类型为A类
。
因为每个子类都知道自己的类型,所以它们在执行 makeCopy()
方法时应该没有问题。这是您的代码中的样子:
for (int i = 0 ; i < another.list.size() ; i++) {
this.list.add(another.list.get(i).makeCopy());
}
注意:此设计称为 prototype pattern ,有时非正式地称为“虚拟构造函数”。
关于java - 抽象类的复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20844660/