Overridden Function within Child Class Constructor (JAVA)
constructor, inheritance, java, overriding
Solution
The superclass constructor is executed first. So when the overridden method is called, the child constructor hasn't been executed yet, so `id` field in the subclass still has its default value.
That's why calling overridable methods from a constructor is a bad practice, flagged by tools such as PMD: the invariants of the objects are not fulfilled when such a method is called.
Problem
Why is the value of id = 0 when super class constructor is called within the derived class constructor? When child object is created, when is memory allotted in the heap for the object? After the base class constructor runs or before? ``` class Parent{ int id = 10; Parent(){ meth(); } void meth(){ System.out.println("Parent :"+ id); } } class Child extends Parent{ int id = 5; Child(){ meth(); } void meth(){ System.out.println("Child :"+ id); } } public class OverRidingEg { public static void main(String[] args) { // TODO Auto-generated method stub Child a= new Child(); } } ```