Given Main.java:
public class Main{
public static void main(String[]args){
A a = new B();
a.print();
}
}
class A{
A() {p
B doesn't have any constructor, so its default constructor won't do anything except calling A's constructor.
Now when B's default constructor is called, it calls A's constructor (keep in mind i
is still not set, so default value 0). A's constructor calls print(), now as object is of actually B it calls B's print() and it prints 0 (remember i
was not set).
Now once these constructor calls completes B's code gets executes which sets i to 0. Now calling print() will again get you to B's print() (as object is of B only) which will print 4.
"DEBUGGING IS THE KEY"