Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override a method which is used in the parent constructor?

Tags:

java

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?

like image 851
eliocs Avatar asked Jan 23 '23 18:01

eliocs


1 Answers

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?

like image 70
Jon Skeet Avatar answered Jan 25 '23 07:01

Jon Skeet