ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
class Base {
public Base() { System.out.print("Base() "); }
}
class Sub extends Base {
public Sub() {
super();
System.out.print("Sub() ");
}
public Sub(int x) {
this();
System.out.print("Sub(int) ");
}
}
public class Main {
public static void main(String[] args) {
new Sub(1);
}
}- A. Base() Sub() Sub(int)
- B. Sub(int) Base() Sub()
- C. Base() Sub(int) Sub()
- D. Compile-time error: a constructor cannot call both this() and super()
Correct answer: A. Base() Sub() Sub(int)
Sub(int) calls this(), redirecting entirely to Sub(). Sub() in turn explicitly calls super() first (running Base(), printing Base()) and then its own body (printing Sub()). Control then returns to Sub(int)'s remaining body, printing Sub(int). Only one of this()/super() is allowed per constructor, and each constructor here only uses one, so there's no conflict.
More OOP with C++ and Java questions
- What is printed? cpp struct Shape { virtual ~Shape() = default; virtual double area() const { return 0; } }; struct Circle : Shape {…
- What is printed? java class Counter { private int count; public synchronized void inc() { count++; } public int get() { return count; } }…
- 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…