ProgrammingHardIBM · Deloitte pattern
What happens when this is compiled?
What happens when this is compiled?
class A {
A(int x) { System.out.print("A(int) "); }
}
class B extends A {
B() { System.out.print("B "); }
}- A. Compiles fine; B() implicitly calls A()
- B. Compile-time error: A has no no-argument constructor, and B() does not explicitly call super(x), so the implicit super() call fails to resolve
- C. Compiles, and B() simply skips calling any A constructor
- D. Compile-time error: a subclass must always redeclare all of its superclass's constructors
Correct answer: B. Compile-time error: A has no no-argument constructor, and B() does not explicitly call super(x), so the implicit super() call fails to resolve
Every constructor implicitly starts with a call to super() (the no-argument superclass constructor) unless it explicitly calls this(...) or super(...). Since A only defines A(int), there is no A() for the compiler to insert, so B() fails to compile unless it explicitly writes super(someInt).
More OOP with C++ and Java questions
- 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 {…
- What is printed? java class Resource { Resource() { System.out.print("open "); throw new RuntimeException("ctor failed"); } void close() {…