Practice mode Java

Given class A { String n() { return “A”; } } class B extends A { String n() { return “B”; } }, what does A o = new B(); System.out.println(o.n()); print?

Correct answer C. B

Explanation

The variable o has static type A, which only decides that the call to n() is legal. At run time the JVM looks at the actual object, a B, and runs its overriding method, so B is printed. This dynamic dispatch lets code written against a superclass work correctly with any subclass.

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.