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();- A. 1 1 1
- B. 0 0 0
- C. 1 2 3
- 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
- What is printed? cpp struct Base { virtual void f() const { cout << "Base-const"; } }; struct Derived : Base { void f() const override {…
- What is printed? java class Shape { double area() { return 0; } } class Circle extends Shape { double radius; Circle(double r) { radius =…
- What is printed? java class Node { Node next; int val; Node(int v) { val = v; } @Override public String toString() { return "N(" + val +…
- What is printed? java class Employee { double bonus() { return 1000; } double pay() { return 50000 + bonus(); } } class Manager extends…
- What is printed? cpp struct Base { Base() { cout << "CtorBase "; } virtual ~Base() { cout << "DtorBase "; } }; struct Derived : Base {…
- What is printed? cpp struct Shape { virtual double area() const { return 0; } virtual void print() const { cout << "Area: " << area(); }…