ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
class Counter {
    private int count = 0;
    void inc() { count++; }
    int get() { return count; }
}
class LoggingCounter extends Counter {
    private int calls = 0;
    @Override
    void inc() { calls++; super.inc(); }
    int calls() { return calls; }
}
public class Main {
    public static void main(String[] args) {
        Counter c = new LoggingCounter();
        c.inc(); c.inc(); c.inc();
        System.out.print(c.get() + " " + ((LoggingCounter) c).calls());
    }
}
  1. A. 0 3
  2. B. 3 0
  3. C. 3 3
  4. D. Compilation error: cannot cast Counter to LoggingCounter

Correct answer: C. 3 3

c.inc() dispatches dynamically to LoggingCounter's override, which increments its own private 'calls' and delegates to Counter's inc() via super, incrementing the private 'count'. After three calls both counters reach 3; the explicit downcast to read calls() is valid because the object really is a LoggingCounter.

More OOP with C++ and Java questions

Exams that ask this topic