I have an abstract class Entity
. Every class extending Entity
will need some default and some customizable setup:
public abstract class Entity {
protected Entity() {
// ... default setup
customSetup();
}
protected abstract void customSetup();
// ...
}
My extending class MyEntity
takes a parameter in the constructor, that will be used in customSetup()
:
public class MyEntity extends Entity {
private Data data;
public MyEntity(Data d) {
super(); // in here customSetup() is called!
data = d;
}
@Override
protected void customSetup() {
codeDependingOn(data); // will throw NPE: data==null yet!
}
}
As comments state, this code won't work.
I could just throw away customSetup()
and put all the custom code after super()
, but having that abstract method makes clearer what you're supposed to put there.
I feel like I'm violating some rule of OOP design. What's the correct way to do what I want?
This is generally a bad idea to call methods which can be overriden from a constructor. The problem is that the class is not yet fully initialized, and when the method is called in a subclass, it may cause trouble.
Take a look at this question: What's wrong with overridable method calls in constructors?, it has a good explanation.
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