ProgrammingHardTCS Digital · Accenture advanced

What does this Java program print? class A { String n = "A"; String get() { return n; } } class B extends A { String n = "B"; String get() { return n; } } public class T { public static void main(String[] args) { A o = new B(); System.out.println(o.n + ((B) o).n + o.get()); } }

  1. A. BBB
  2. B. ABB
  3. C. AAB
  4. D. AAA

Correct answer: B. ABB

Fields are not overridden, they are hidden and resolved by the reference's static type: o.n is A's n, ((B) o).n is B's n. The method get() is dispatched dynamically to B and returns B's n, giving ABB.

More OOP with C++ and Java questions

Exams that ask this topic