ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class Counter {
    private int count;
    public synchronized void inc() { count++; }
    public int get() { return count; }
}
class FastCounter extends Counter {
    @Override
    public void inc() { for (int i = 0; i < 2; i++) super.inc(); }
}
public class Main {
    public static void main(String[] args) {
        FastCounter c = new FastCounter();
        c.inc();
        c.inc();
        System.out.println(c.get());
    }
}
  1. A. 2
  2. B. 4
  3. C. Compile-time error: cannot override a synchronized method with a non-synchronized one
  4. D. 1

Correct answer: B. 4

synchronized is a modifier affecting locking behaviour, not part of the method's signature, so an override may freely add or drop it; this compiles fine. Each call to c.inc() runs FastCounter's override, which calls super.inc() (the real increment) twice; two outer calls therefore increment count four times total, giving 4.

More OOP with C++ and Java questions

Exams that ask this topic