ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
class A {
A() { System.out.print(id() + " "); }
int id() { return 0; }
}
class B extends A {
int val;
B(int v) { val = v; }
@Override
int id() { return val; }
}
public class Main {
public static void main(String[] args) {
B b = new B(7);
System.out.print(b.id());
}
}- A. 0 7
- B. 0 0
- C. 7 7
- D. Compile-time error: val is final at the point A's constructor runs
Correct answer: A. 0 7
A's constructor runs before B's constructor body sets val = 7; at that moment val still holds its default value 0, and id() dispatches dynamically to B's override, printing 0. Later, after full construction, b.id() correctly reads the now-set val, printing 7. Total: 0 7.
More OOP with C++ and Java questions
- What is printed? cpp struct Shape { virtual void draw() const { cout << "Shape "; } }; struct Group : Shape { std::vector<Shape> children…
- What is printed? cpp struct A { virtual void f() { cout << "A"; } }; struct B : A { void f() override { cout << "B"; } }; struct C : B {…
- Does this compile? java public class Main { public static void main(String[] args) { try { throw new RuntimeException("x"); } catch…
- What is printed? java public class Main { public static void main(String[] args) { try { Object[] arr = new String[3]; arr[0] = 100; }…
- What is printed? cpp void f() { try { throw 10; } catch (double d) { cout << "double:" << d; } catch (int i) { cout << "int:" << i; } }…
- What is printed? java public class Main { public static void main(String[] args) { int[] arr = {1, 2, 3}; try {…