A way for this to be avoided is by exposing an init
method (or any other name) from your base class (if you are in control of its logic). Then move the call from the constructor to the init method:
public class A {
public A() {
}
public void init() {
doSomething();
}
public void doSomething() {
}
}
You should update your code to call the init
method after making an instance of the class, which may be a bit of boilerplate:
A instance = new Wrapper();
instance.init();
instead of just
A instance = new Wrapper();
If you use Spring and DI, you can specify an init-method
in the xml context, so Spring will call it for you when it resolves the dependency.
In case the doSomething
method is public, and accepts no arguments, you can use it directly instead of the init
method both in code and with Spring.
In general, use of overridable methods in a constructor is an anti-pattern, due to the problem you have encountered. There is no way to predict how a derived class will override the methods and if they rely on non-initialized resources, then you are in trouble.