tags:

views:

120

answers:

2

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?

+2  A: 

The child a() will be called.

Your assumption that calling a() from constructor will not call the overriding method is correct in C++ but not in Java. Indeed initialization of the fields of the subclass will not have occurred but still the language allows overriding in calling a method from a constructor.

[edit]

Clearly you should be careful with such calls and they are generally considered a risky practice.

Itay
..and this will cause problems.
Adam Woś
+6  A: 

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?

Jon Skeet
I need to use properties that are defined in the child class, I can change the design of the upper class.
eliocs
Can the child constructor pass the information up to the super class constructor via constructor arguments?
Jon Skeet
I thought of that option but it didn't seem as the best option, I'm thinking of separating the a() method from the constructor and make the child constructor call super() and then a()
eliocs
It can be a problem, but IF the child a method doesn't use something initialized in the child constructor is ok. Anyway: probably it'll need it :) (in fact, it happened to me 3 days ago :)
helios