简体   繁体   English

复制抽象类的构造函数

[英]Copy constructor for abstract class

I have an abstract class named AClass . 我有一个名为AClass的抽象类。 In the same package I have AnotherClass , in which I have an ArrayList of AClass objects. 在同一个包中我有AnotherClass ,其中我有一个AClass对象的ArrayList In the copy constructor of AnotherClass I need to make a duplicate of AClass objects inside the ArrayList . AnotherClass的复制构造函数中,我需要在ArrayList复制AClass对象。

The problem: 问题:

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 . 我无法在AClass创建一个复制构造函数,因为它是一个抽象类,我不知道将由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 . 实际上,在这个项目中,没有对象会从这个类继承,但是这个项目将被其他项目用作库,这些项目将提供一个AClass类。 Is there an error in my design or is there a solution to this problem? 我的设计中是否有错误或是否有解决此问题的方法?

Edit : here's some code: 编辑 :这是一些代码:

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 by AClass 我不能在AClass创建一个复制构造函数,因为它是一个抽象类,我不知道将由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: 但是,由于您有一个AClass列表, AClass您无需知道确切的子类型:创建副本的抽象函数就足够了:

protected abstract AClass makeCopy();

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 . 这类似于java.lang.Objectclone()函数,除了所有子类都必须实现它,并且返回类型必须是AClass

Since each subclass knows its own type, they should have no problem implementing makeCopy() method. 由于每个子类都知道自己的类型,因此实现makeCopy()方法应该没有问题。 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". 注意:这种设计被称为原型模式 ,有时非正式地称为“虚拟构造函数”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM