如何在BaseClass复制构造函数中复制SubClass对象 [英] how to copy SubClass object in BaseClass copy constructor

查看:85
本文介绍了如何在BaseClass复制构造函数中复制SubClass对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在BaseClass构造函数中复制SubClass对象。我需要以下代码正确执行。

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?

推荐答案

这是不可能的。类A的构造函数为您提供了A的实例,无法绕开它。为什么不显式实例化子类?

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
}

这篇关于如何在BaseClass复制构造函数中复制SubClass对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆