how to copy SubClass object in BaseClass copy constructor

烂漫一生 提交于 2019-12-02 17:38:36

问题


I would like to make copy of SubClass object in BaseClass constructor. I need that the following code execute correctly.

class BaseClass{
    BaseClass() {}
    BaseClass(BaseClass base) {
        //TODO: how to implement?
    }
}

class SubClass extends BaseClass {    
   SubClass() {}
}

public class Test {
    public static void main(String[] args) {

        BaseClass sub = new SubClass();
        BaseClass subCopy = new BaseClass(sub);
        if (subCopy instanceof SubClass) {
            // need to be true
        }
    }
}

Is it even possible? If yes how can I do it? Else how can I get similar effect?


回答1:


It's not possible. A constructor of class A gives you an instance of A, no way to circumvent this. Why not instantiate the subclass explicitly?

Another possibility might involve a static factory method like:

public static BaseClass create(BaseClass input) {
       // return BaseClass or subclass
}



回答2:


It seems like you want the object of BaseClass to be an instance of SubClass which extends BaseClass.

Is it even possible?

-No. It is not possible.

The instanceof operator returns true if the variable on left side satisfies IS-A condition of the variable or class on the left side.

The SubClass IS-A BaseClass since it extends BaseClass. But the BaseClass can never be a SubClass, since it can't extend SubClass.




回答3:


You seems to be having a design upside-down. If you need to do what you are asking then you need to re-think over your design. Ideally in your subclass constructor, you should be copying or initializing the base class properties by calling super().



来源:https://stackoverflow.com/questions/16882623/how-to-copy-subclass-object-in-baseclass-copy-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!