开发者

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 cons开发者_开发问答tructor 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);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜