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()); } }
- A. BBB
- B. ABB
- C. AAB
- 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
- What does this Java program print? class P { P() { init(); } void init() { System.out.print("P "); } } class C extends P { int x = 5; C()…
- What does this Java code print? Integer a = 127, b = 127, c = 128, d = 128; System.out.println((a == b) + " " + (c == d) + " " +…
- What does this Java code print? class A { String n = "A"; String get() { return n; } } class B extends A { String n = "B"; String get() {…
- What does this Java program print? class P { static { System.out.print("1"); } { System.out.print("2"); } P() { System.out.print("3"); } }…
- What does this Java program print? static int f() { int x = 1; try { return x; } finally { x = 3; } } static int g() { try { throw new…
- What does this C++ program print? struct B { B() { f(); } virtual void f() { std::cout << "B"; } }; struct D : B { D() { f(); } void f()…