I'm having a design problem which I don't know how to overcome in java. I want to override a method that is called from the parent constructor. Here is a very simple example of the problem:
public class Parent {
public Parent(){
a();
}
public void a() {
// CODE
return;
}
}
public class Child extends Parent {
public Child() {
super();
}
public void a() {
super.a();
// MORE CODE
return;
}
}
I know that the child class wont be initialized until the parent is constructed therefore the childs a() method wont be called. What is the correct design to overcome this problem?
The child override will be called - but the child constructor won't have executed yet, so unless it's designed to be invoked on a partially initialized object, you could easily have a problem. The best approach is not to call virtual methods in contructors. It just is a problem. Are you in control of both classes? Can you redesign to avoid the problem in the first place?
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