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());
}
}- A. 2
- B. 4
- C. Compile-time error: cannot override a synchronized method with a non-synchronized one
- 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
- What is printed? java class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) {…
- What is printed? java public class Main { public static void main(String[] args) { String a = "hello"; String b = "hello"; String c = new…
- What is printed? java public class Main { public static void main(String[] args) { String a = new String("hi").intern(); String b = "hi"…
- What is printed? java class Box { int value; Box(int v) { value = v; } } public class Main { public static void main(String[] args) { Box…
- Which statement about overriding equals() correctly describes the contract that must hold?
- What is printed? java class Animal { String name; Animal(String n) { name = n; } @Override public boolean equals(Object o) { if (!(o…