ProgrammingHardHCL · Tech Mahindra pattern

What happens when this Java code is compiled?

What happens when this Java code is compiled?
class P { P(int x) { } }
class C extends P { C() { } }
  1. A. Compilation error: C() implicitly calls super(), and P has no no-argument constructor
  2. B. It compiles; Java adds P() automatically
  3. C. It compiles but throws an error when a C is created
  4. D. It compiles because C's constructor is empty

Correct answer: A. Compilation error: C() implicitly calls super(), and P has no no-argument constructor

Every constructor starts with super(...) and the compiler inserts super() if you write nothing. Since P declares a constructor, no default P() exists, so C() must call super(someInt) explicitly.

More OOP with C++ and Java questions

Exams that ask this topic