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());
    }
}
  1. A. 0 7
  2. B. 0 0
  3. C. 7 7
  4. 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

Exams that ask this topic