Given class A { A() { show(); } void show() { System.out.print(“A”); } } class B extends A { int x = 5; void show() { System.out.print(x); } }, what does new B(); print?
Correct answer B. 0
Explanation
The constructor of A runs before B's field initialisers. Its call to show() is dispatched to B's override because the object really is a B, but x has not yet been assigned 5, so its default value 0 is printed. This is why calling overridable methods from a constructor is considered dangerous.
Answer checked How we write and check questions
Discussion