4

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();

        }

    }
theIronGiant
  • 135
  • 5
  • 14
  • I don't see any call to `super()` ... How is the parent constructor called ? – LaGrandMere Mar 21 '13 at 15:57
  • 2
    @LaGrandMere every no-args default sub-class constructor will have an implicly super() call if the parent class has no-args default cons – PermGenError Mar 21 '13 at 15:58
  • @PermGenError: every subclass constructor will have such an implicit call, even the ones with arguments. – JB Nizet Mar 21 '13 at 15:59
  • @JBNizet yepp, but my intention was if parent class doesn't have an default cons, then the sub-class cons should explicitly make a super call. :) – PermGenError Mar 21 '13 at 16:00

1 Answers1

5

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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255