how to copy SubClass object in BaseClass copy constructor

前端 未结 3 698
清歌不尽
清歌不尽 2021-01-28 10:53

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

class BaseClass{
    BaseClass() {}
             


        
相关标签:
3条回答
  • 2021-01-28 11:25

    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.

    0 讨论(0)
  • 2021-01-28 11:28

    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
    }
    
    0 讨论(0)
  • 2021-01-28 11:31

    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().

    0 讨论(0)
提交回复
热议问题