简体   繁体   中英

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

Second, you need to instantiate your parent like this

Parent p = new Child();

Child c = (Child) p;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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