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());
- A. BB
- B. AA
- C. BA
- 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
- 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()…
- What does this C++ program print? struct B { virtual void f(int x = 1) { std::cout << "B" << x; } }; struct D : B { void f(int x = 2)…
- What is printed? (C++17, assume <iostream> and using namespace std) cpp struct B { virtual void f(int x = 1) { cout << "B" << x; } }…
- What is printed? (C++17, assume <iostream> and using namespace std) cpp struct B { void f(int) { cout << "Bi"; } void f(double) { cout <<…