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.
Answer checked How we write and check questions
Discussion