ProgrammingHardTCS NQT · Infosys · Accenture

What does this Java code print? class A { String n = "A"; String get() { return n; } } class B extends A { String n = "B"; String get() { return n; } } // in main: A o = new B(); System.out.println(o.n + o.get());

  1. A. BB
  2. B. AA
  3. C. BA
  4. D. AB

Correct answer: D. AB

Fields are not overridden, they are hidden, and field access is resolved by the static type A, so o.n is "A". Methods are dispatched on the runtime type B, so o.get() returns B's own field "B".

More OOP with C++ and Java questions

Exams that ask this topic