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();
}
}
Instance field initializers run after the superclass constructor has been called. So the order of execution is:
new B()
B
:super()
A
A.a
as 100myMethod
, which is overridden in B
B.a
which is 0A
constructor returnsB.a
as 200B
constructor, which is emptyAs 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.
See more on this question at Stackoverflow