Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheriting a class with constructor arguments in java

Tags:

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.

like image 376
palto Avatar asked Oct 10 '22 11:10

palto


1 Answers

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;
    }
}
like image 150
Jon Skeet Avatar answered Oct 13 '22 02:10

Jon Skeet