ProgrammingHardHCL · Tech Mahindra pattern
What is printed?
What is printed?
class Base {
static int shared = 0;
int id;
Base() { id = ++shared; }
}
class Sub extends Base {
}
public class Main {
public static void main(String[] args) {
Base b1 = new Base();
Sub s1 = new Sub();
Base b2 = new Base();
System.out.println(b1.id + " " + s1.id + " " + b2.id + " " + Base.shared);
}
}- A. 1 1 1 1
- B. 1 2 3 3
- C. 0 1 2 3
- D. 1 2 2 3
Correct answer: B. 1 2 3 3
shared is a single static field shared by Base and every subclass. Each construction (b1, s1, b2) runs Base's constructor (directly or via the implicit super() call in Sub), incrementing the shared counter once each time: b1.id=1, s1.id=2, b2.id=3, and the final Base.shared is 3.
More OOP with C++ and Java questions
- What is printed? java class Base { Base(String tag) { System.out.print("Base:" + tag + " "); } } class Sub extends Base { Sub() {…
- What is printed? cpp struct Shape { virtual double area() const = 0; bool operator<(const Shape &o) const { return area() < o.area(); } }…
- What is printed? java class Matrix { int[][] data; Matrix(int n) { data = new int[n][n]; } @Override public boolean equals(Object o) { if…
- What is printed? java class Vehicle { void honk() { System.out.print("Beep "); } } class Car extends Vehicle { @Override void honk() {…
- What is printed? java List<String> strings = new ArrayList<>(); List<Integer> ints = new ArrayList<>()…
- What is printed? java class Holder<T extends Number> { T value; Holder(T v) { value = v; } double asDouble() { return value.doubleValue()…