复制抽象类的构造函数 [英] Copy constructor for abstract class
问题描述
我有一个名为 AClass
的抽象类。在同一个包中我有 AnotherClass
,其中我有一个 ArrayList
AClass
对象。在 AnotherClass
的复制构造函数中,我需要在 ArrayList中复制
。 AClass
对象
I have an abstract class named AClass
. In the same package I have AnotherClass
, in which I have an ArrayList
of AClass
objects. In the copy constructor of AnotherClass
I need to make a duplicate of AClass
objects inside the ArrayList
.
问题:
我无法在 AClass $中创建复制构造函数c $ c>因为它是一个抽象类,我不知道将由
AClass
继承的类的名称。实际上,在这个项目中,没有对象会从这个类继承,但是这个项目将被其他项目用作库,这些项目将提供 AClass
的类子项。我的设计中是否有错误或是否有解决此问题的方法?
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 by AClass
. Actually, in this project, no object will inherit from this class, but this project will be used as a library by other projects which will provide a class child of AClass
. Is there an error in my design or is there a solution to this problem?
编辑:这里有一些代码:
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
}
}
...
}
推荐答案
我无法在
AClass $中创建复制构造函数c $ c>因为它是一个抽象类,我不知道将继承的类的名称
AClass
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
的列表,您不需要知道确切的子类型:创建副本的抽象函数就足够了:
This is generally correct. However, since you have a list of AClass
, you do not need to know the exact subtype: an abstract function that make a copy would be sufficient:
protected abstract AClass makeCopy();
这类似于 clone()
java.lang.Object
的函数,除了所有子类必须实现它,并且返回类型必须是 AClass
。
This is similar to the clone()
function of the java.lang.Object
, except all subclasses must implement it, and the return type is required to be AClass
.
由于每个子类都知道自己的类型,因此实现 makeCopy()
方法应该没有问题。以下是您的代码中的内容:
Since each subclass knows its own type, they should have no problem implementing makeCopy()
method. Here is how this would look in your code:
for (int i = 0 ; i < another.list.size() ; i++) {
this.list.add(another.list.get(i).makeCopy());
}
注意:此设计称为 原型模式 ,有时非正式地称为虚拟构造函数。
Note: this design is known as the prototype pattern, sometimes informally called the "virtual constructor".
这篇关于复制抽象类的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!