Question
Why does an overridden method get executed before the constructor in Java?
Answer
In Java, the flow of execution during object instantiation can sometimes lead to confusion. Specifically, when an overridden method is called, it may appear to execute before the constructor of the parent class, leading to the question: why does this happen? This phenomenon is deeply rooted in the concepts of inheritance and dynamic method dispatch within Java.
class Parent {
Parent() {
display(); // Calls the overridden method
}
void display() {
System.out.println("Parent display");
}
}
class Child extends Parent {
Child() {
super();
}
@Override
void display() {
System.out.println("Child display");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child(); // Outputs "Child display"
}
}
Causes
- The method overriding in Java allows a subclass to provide a specific implementation of a method that is already defined in its superclass.
- When an object of a subclass is created, the constructor of the subclass is executed. However, if the subclass's constructor calls an overridden method, the method defined in the subclass is executed before the superclass's constructor completes.
Solutions
- To ensure that the constructor's code is executed before any overridden methods, avoid calling methods that can be overridden in the constructor of the superclass or subclass until after the construction is complete.
- Use a different method structure or a factory pattern wherein the object is fully initialized before invoking any methods that rely on inherited states.
Common Mistakes
Mistake: Calling an overridden method in a superclass constructor.
Solution: Refactor code to ensure that overridden methods are not invoked in the constructor of a superclass.
Mistake: Not understanding dynamic method dispatch.
Solution: Study how polymorphism works in Java and how method overriding influences the flow.
Helpers
- Java method overriding
- Java constructor execution
- Java inheritance
- Java flow of execution
- Overridden method vs constructor
- Java polymorphism