简体   繁体   中英

Inheriting a class with constructor arguments in java

The situation is I want to inherit an object to have a cleaner constructor interface:

class BaseClass {
    public BaseClass(SomeObject object){
        ...
    }
}

class SubClass extends BaseClass{
    private SubObject subObject = new SubObject();
    public SubClass(){
        super(new SomeObject(subObject)); // doesn't compile
    }
}

But to do that I need to do stuff before the constructor like in the example above but can't because Java doesn't allow that. Is there any way around this? I'm starting to feel that if your class is designed to be subclassed it should always implement default constructor and provide setters for the values it needs... Sometimes you can get away with this if you create a new object straight into the super constructor as an argument but if you need a reference to the object you created then you are hosed.

You need to change it so that you're not referring to an instance member in the superconstructor call. Unfortunately if you need to then "save" the SubObject , it becomes tricky. I think you'd have to do it with constructor chaining:

class SubClass extends BaseClass{
    private SubObject subObject;

    public SubClass() {
        this(new SubObject());
    }

    private SubClass(SubObject subObject) {
        super(new SomeObject(subObject));
        this.subObject = subObject;
    }
}
public SubClass(){
    super(new SomeObject(new SubObject())); // this should compile
}

Now in your super class, do something like this:

private final SomeObject foo;
public BaseClass(SomeObject foo){
    this.foo = foo;
}
public /* or protected */ SomeObject getFoo(){return this.foo;}

Not exactly an answer since you would have no SubClass , but you could use a factory.

public BaseClassFactory {
    public static BaseClass newBaseClass() {
        // init some object
        // ...
        return new BaseClass(someObject);
    }
}

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