简体   繁体   中英

Make derived class instance given base class instance in Java

I have this situation where

class Parent {
    int data;
    public Parent(int data) {
        this.data = data;
    }
}

class Child extends Parent {
    int childData;
    public Child(int data, int childData) {
        super(data);
        this.childData = childData;
    }
}

And on hand I have an instance of Parent . I want to add the childData functionality to it. I've recently been programming in Javascript where this is trivial, and I mentally ported over the design patterns without realizing this is nontrivial in Java.

Assuming I have full control over Child class code, what is the best practice to do this? Can I do this without cloning? Is it necessary to modify Parent class to get this to work?

Of course in the worst case (this sounds awful) there is this solution:

new Child(parent.data, childData);

Since Parent 's data are all public.

Specific problem (which I tend to forget to include on Java questions) is I have a Config.testUser method which returns user, and I would like to add one datum to it to make it an InitialScanUser , which is a User with an initialScanAlgorithm datum of type InitialScanAlgorithm added. Config.testUser lives in a package which cannot depend on InitialScanAlgorithm .

Make Parent instances immutable and you can just delegate to an instance of Parent .

See Effective Java, Item 16: Favor composition over inheritance.

It is not trivial. An instance class cannot be changed (although it can be referenced as a superclass reference, but the instance itself cannot change).

A more elegant way would be (if you use the construct a lot) to add a constructor that accepts a parent instance.

public Child(Parent parent, int childData) {
  ....
}

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