Why is variable not printing correctly?

Why did the following program output Method B 0 instead of Method B 200? I can't understand what my problem is.

class A{
    int a=100;
    void myMethod(){
        System.out.println("myMethod of A : "+a);
    }
    A(){
        myMethod();//calling my method
    }
}
class B extends A{
    int a=200;
    void myMethod(){
        System.out.println("myMethod of B : "+a);
    }
 }
 class Demo{
     public static void main(String args[]){
         new B();
     }
 }
Jon Skeet
people
quotationmark

Instance field initializers run after the superclass constructor has been called. So the order of execution is:

  • Call to new B()
  • Start to initialize instance of B:
  • Implicitly call super()
    • Start to initialize the instance with respect to A
    • Initialize field A.a as 100
    • Call myMethod, which is overridden in B
    • Print out B.a which is 0
    • A constructor returns
  • Initialize field B.a as 200
  • Execute the body of the B constructor, which is empty

As you can see, your println call occurs when the B.a field hasn't been initialized yet.

This is why executing methods which have been overridden (in your case myMethod()) from a constructor is so dangerous - it can end up working with state which hasn't gone through its normal initialization yet.

people

See more on this question at Stackoverflow