ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
class Base {
Base(String tag) { System.out.print("Base:" + tag + " "); }
}
class Sub extends Base {
Sub() { super(makeTag()); System.out.print("Sub "); }
static String makeTag() { return "generated"; }
}
public class Main {
public static void main(String[] args) { new Sub(); }
}- A. Sub Base:generated
- B. Base:generated Sub
- C. Compile-time error: cannot call a static method before super() finishes
- D. Base:null Sub
Correct answer: B. Base:generated Sub
Arguments to super(...) must be evaluable before the superclass constructor actually runs, and static methods of the subclass are allowed there since they don't depend on instance state. makeTag() runs first, returning "generated"; Base's constructor then prints Base:generated; only afterward does Sub's own body print Sub.
More OOP with C++ and Java questions
- 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()…
- What is printed? java class Util { static <T> void swap(T[] arr, int i, int j) { T tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } } public…