Practice mode Java

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.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.