Practice mode Java

Given class A { int v = 1; } class B extends A { int v = 2; }, what does A o = new B(); System.out.println(o.v); print?

Correct answer C. 1

Explanation

Fields are not polymorphic. B's field v merely hides A's field, and the object contains both. The expression o.v is resolved at compile time from the static type A, so A's v is read and 1 is printed. Choosing 2 wrongly applies the dynamic dispatch rule, which covers only instance methods.

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.