简体   繁体   English

从超类Java实例化子类

[英]Instantiate subclass from superclass Java

I want to try and instantiate a Child object that extends Parent with the properties of a previously instantiated parent object. 我想尝试实例化使用先前实例化的父对象的属性扩展了Parent的Child对象。 So something like this: 所以像这样:

class Parent {
    ClassName property1;

    // Setters and getters
}

class Child extends Parent {
    public Child(Parent parent) {
        this.property1 = parent.getProperty1();
        // + other properties
    }
}

Parent parent = new Parent();
parent.setProperty1(prop);

Child object = (Child)parent; // Casting exception
Child object2 = new Child(parent); // This is not ideal

Is there any other way to achieve this? 还有其他方法可以做到这一点吗?

First look up polymorphism. 首先查找多态性。 It seems you're not familiar with one of the main features of an OOP language. 似乎您并不熟悉OOP语言的主要功能之一。

Second, you need to instantiate your parent like this 其次,您需要像这样实例化您的父母

Parent p = new Child();

Child c = (Child) p;

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

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