ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class Counter {
    protected int count = 0;
    void inc() { count++; }
}
class LoggingCounter extends Counter {
    @Override
    void inc() { super.inc(); System.out.print(count + " "); }
}
// in main:
Counter c = new LoggingCounter();
c.inc();
c.inc();
c.inc();
  1. A. 1 1 1
  2. B. 0 0 0
  3. C. 1 2 3
  4. D. Compile-time error: inc() has no return value to log

Correct answer: C. 1 2 3

c's runtime type is LoggingCounter, so every c.inc() call dispatches to the override. Each call first runs super.inc() (incrementing the shared count field inherited from Counter), then prints the new value, giving 1 2 3.

More OOP with C++ and Java questions

Exams that ask this topic