ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
class A {
A() { this(10); System.out.print("A() "); }
A(int x) { System.out.print("A(int)=" + x + " "); }
}
public class Main {
public static void main(String[] args) { new A(); }
}- A. A() A(int)=10
- B. A(int)=10 A()
- C. Compile-time error: this(10) and the default super() call conflict
- D. A(int)=10 A() A(int)=10
Correct answer: B. A(int)=10 A()
this(10) redirects construction to A(int), which runs to completion first (its own implicit super() to Object runs silently, then it prints A(int)=10). Control then returns to A()'s remaining body, which prints A(). Result: A(int)=10 A().
More OOP with C++ and Java questions
- What is printed? cpp struct Base { Base() { cout << "Base() "; } Base(int x) { cout << "Base(int) "; } }; struct Derived : Base {…
- What is printed? java class Resource { Resource() { System.out.print("open "); throw new RuntimeException("ctor failed"); } void close() {…
- What is printed? cpp struct Base { virtual ~Base() { cout << "~Base "; } }; struct Mid : Base { ~Mid() { cout << "~Mid "; } }; struct Leaf…
- What is printed? java class Animal { Animal() { System.out.print(category() + " "); } String category() { return "Animal"; } } class Bird…
- What is printed? cpp struct Base { Base() { cout << "Base "; } Base(const Base&) { cout << "BaseCopy "; } }; struct Derived : Base {…
- What is printed? cpp int f() { std::cout << "f "; return 1; } int g() { std::cout << "g "; return 2; } int a = f(); int b = g(); int…