How to override the method that is used in the parent constructor?

I have a design problem that 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 a 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 will not be initialized until the parent is created, so the childs a () method will not be called. What is the right design to solve this problem?

+4
source share
2 answers

A child override will be called, but the child constructor has not yet been executed, so if it is not intended to be called on a partially initialized object, you may have a problem. The best approach is not to invoke virtual methods in constructors. This is just a problem. Do you control both classes? Can you redesign to avoid the problem in the first place?

+7
source

The child of a () is called.

Your assumption that calling a () from the constructor will not call the override method is correct in C ++, but not in Java. In fact, the initialization of the fields of the subclass did not occur, but still the language allows you to override the method call from the constructor.

[edit]

Obviously, you must be careful with such challenges, and they are usually considered a risky practice.

+2
source

All Articles