Consider the following code segment:
class A{ /* assume static and non static block are here */ }
class B extends A{ /* assume static and non static block are here */ }
In main method,
new B();
So the order of the initialization would be :
- static members initialization for class A
- static members initialization for class B
- non static members initialization for class A
- then execute the code inside constructor A
- non static members initialization for class B
- then execute the code inside constructor B
Now take a look at this code segment,
class A{
A(){
this.m(); //line 1
}
void m(){
System.out.println("A.m()");
}
}
class B extends A{
void m(){
System.out.println("B.m()");
}
}
In main method,
new B();
When the code of constructor A is being executed, it can only see the method m in class A since non static members hasn't been initialized yet for class B (according to the order I mentioned). However the result is "B.m()". (method of sub class has been executed) Can someone explain what is happening here(method overridng) considering the order that I have mentioned ?