Java inheritance and constructors: given A has only A(int) and B extends A with no explicit constructor, what happens when creating new B()? class A { public A(int x){} } class B extends A {} public class test { public static void main(String[] args) { A a = new B(); System.out.println("complete"); } }

Difficulty: Easy

Correct Answer: Compile Error

Explanation:


Introduction / Context:
This problem targets Java constructor chaining rules. If a superclass lacks a no-argument constructor, a subclass must explicitly invoke a matching super(...) constructor; otherwise, the compiler-inserted super() call fails.


Given Data / Assumptions:

  • Class A declares only A(int).
  • Class B declares no constructors.
  • The main method attempts new B() via assignment to A.


Concept / Approach:
When no constructor is written for B, the compiler synthesizes a no-arg constructor that calls super(). Because A has no no-arg constructor, this synthetic call is invalid and compilation fails with “constructor A in class A cannot be applied to given types…”.


Step-by-Step Solution:
Check superclass A: only A(int).Subclass B: no constructors ⇒ implicit no-arg constructor inserted.Implicit constructor calls super(), but A has no such constructor.Therefore, compilation error occurs; the program never runs.


Verification / Alternative check:
Add B(){ super(0); } and recompile; code will then compile and print “complete”.


Why Other Options Are Wrong:
Options A/D/E assume successful compilation; Option B suggests runtime failure, but the error is detected at compile time.


Common Pitfalls:
Forgetting that the compiler always inserts a super() call if you do not specify a constructor in the subclass.


Final Answer:
Compile Error

More Questions from Java.lang Class

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion