ProgrammingVery hardProduct-company MCQ pattern
What is printed?
What is printed?
class A {
A() { System.out.print("A "); init(); }
void init() { System.out.print("A.init "); }
}
class B extends A {
int x = 10;
B() { System.out.print("B "); }
void init() { System.out.print("x=" + x + " "); }
}
// in main:
new B();- A. A x=10 B
- B. A x=0 B
- C. A x=0 B x=10
- D. A B x=10
Correct answer: B. A x=0 B
Java's constructor chaining implicitly calls the superclass constructor first; inside A's constructor, the virtual call init() dispatches to B's override (because the object's actual runtime type is already B), but B's field x has not yet been initialized at this point (field initializers run after the super() call completes, right before B's own constructor body), so x reads as its default value 0.
More OOP with C++ and Java questions
- What is printed? java public int test() { try { return 1; } finally { System.out.println("finally"); } } // caller…
- What is printed? java public int test() { try { return 1; } finally { return 2; } } // caller prints test()
- What is printed? java class MyChecked extends Exception {} class Test { static void risky() throws MyChecked { throw new MyChecked(); }…
- What is printed? java try { try { throw new RuntimeException("inner"); } finally { System.out.print("inner-finally "); } } catch…
- What is printed? java class A { } class B extends A { } class Test { public static void main(String[] args) { A a = new B(); try { B b =…
- What is printed? java List<String> strings = new ArrayList<>(); List<Integer> ints = new ArrayList<>()…