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 "); }
}
  1. A. Compiles fine; B() implicitly calls A()
  2. 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
  3. C. Compiles, and B() simply skips calling any A constructor
  4. 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

Exams that ask this topic