This is the code in Java language:
class A{
A() { print(); }
void print() { System.out.println("A"); }
}
class B extends A{
int i = Math.round(3.5f);
public static void main(String[] args){
A a = new B();
a.print();
}
void print() { System.out.println(i); }
}
It prints 0, 4.
But why does from the super class A within constructor you invoke subclass print method? I see that the print method is overridden, but in fact the ‘print’ method has been called from the superclass…
That is the drill in order to prepare for Java certification.
Best regards
Don’t invoke
printin the constructur ofA. This is where it prints0, because the instance ofBapparently isn’t fully initialized yet, and the value ofB.iapparently still is0.The implicit constructor of
Bis:As you can see, print gets executed before
iis initialized. Yet, you have overriddenprint, the old print is never executed.