ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
class Base {
    static int shared = 0;
    int id;
    Base() { id = ++shared; }
}
class Sub extends Base {
}
public class Main {
    public static void main(String[] args) {
        Base b1 = new Base();
        Sub s1 = new Sub();
        Base b2 = new Base();
        System.out.println(b1.id + " " + s1.id + " " + b2.id + " " + Base.shared);
    }
}
  1. A. 1 1 1 1
  2. B. 1 2 3 3
  3. C. 0 1 2 3
  4. D. 1 2 2 3

Correct answer: B. 1 2 3 3

shared is a single static field shared by Base and every subclass. Each construction (b1, s1, b2) runs Base's constructor (directly or via the implicit super() call in Sub), incrementing the shared counter once each time: b1.id=1, s1.id=2, b2.id=3, and the final Base.shared is 3.

More OOP with C++ and Java questions

Exams that ask this topic