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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With