ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
class A {
A() { System.out.print("A "); }
}
class B extends A {
B() { System.out.print("B "); }
B(int x) { this(); System.out.print("B(int) "); }
}
public class Main {
public static void main(String[] args) { new B(5); }
}- A. B(int) A B
- B. A B B(int)
- C. B A B(int)
- D. Compile-time error: this() and the implicit super() call cannot both run
Correct answer: B. A B B(int)
this() in B(int) redirects to B's no-arg constructor instead of letting the compiler insert an implicit super() call directly. B() in turn has its own implicit super() call to A() first (printing A), then its own body (printing B); control then returns to B(int), which prints B(int). Result: A B B(int).
More OOP with C++ and Java questions
- What happens when this is compiled? java class A { A(int x) { System.out.print("A(int) "); } } class B extends A { B() {…
- What is printed? cpp struct A { A() { cout << "A"; } ~A() { cout << "~A"; } }; struct B { A a; B() { cout << "B"; } ~B() { cout << "~B"; }…
- What is printed? java class Base { protected int val; Base(int v) { val = v; System.out.print("Base(" + val + ") "); } } class Derived…
- What is printed? cpp struct Logger { Logger(string tag) : tag(tag) { cout << "open-" << tag << " "; } ~Logger() { cout << "close-" << tag…
- What is printed? java class A { A() { this(10); System.out.print("A() "); } A(int x) { System.out.print("A(int)=" + x + " "); } } public…
- What is printed? cpp struct Base { Base() { cout << "Base() "; } Base(int x) { cout << "Base(int) "; } }; struct Derived : Base {…