ProgrammingVery hardTCS Digital · Infosys SP
What does this Java program print? class P { P() { init(); } void init() { System.out.print("P "); } } class C extends P { int x = 5; C() { super(); System.out.print(x + " "); } void init() { System.out.print(x + " "); } } public class T { public static void main(String[] a) { new C(); } }
- A. 5 5
- B. P 5
- C. 0 5
- D. P 0
Correct answer: C. 0 5
The superclass constructor runs first and calls the overridden init() of C before C's field initialisers execute, so x still has its default 0. After super() returns x is set to 5 and the constructor prints it.
More OOP with C++ and Java questions
- 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()…
- 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)…