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());
}
}- A. 0 3
- B. 3 0
- C. 3 3
- 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
- What is printed? java String a = "hel" + "lo"; String b = "hello"; System.out.println(a == b);
- Which statement about this code is correct? java class P { P(int x) { System.out.print("P" + x + " "); } } class C extends P { C() {…
- What is printed? cpp struct Base { virtual void show() { cout << "Base "; } }; struct Derived : Base { void show() override { cout <<…
- What is printed? java // in main: List<String> ls = new ArrayList<>(); List<Integer> li = new ArrayList<>()…
- Which statement about this class is correct? java class Example<T> { void method(List<String> list) { System.out.println("string-list"); }…
- What is printed? java class Util { static <T> T firstNonNull(T a, T b) { return a != null ? a : b; } } // in main: String s =…