Java constructor chaining: subclass must invoke a superclass constructor; what is the outcome here?\n\nclass Super {\n public int i = 0;\n public Super(String text) { i = 1; }\n}\nclass Sub extends Super {\n public Sub(String text) { i = 2; }\n public static void main(String args[]) {\n Sub sub = new Sub("Hello");\n System.out.println(sub.i);\n }\n}

Difficulty: Easy

Correct Answer: Compilation fails.

Explanation:


Introduction / Context:
The example validates understanding of constructor chaining in Java. If a superclass defines no no-argument constructor, every subclass constructor must explicitly invoke one of the existing superclass constructors using super(...). Otherwise, the compiler inserts an implicit super() that does not exist, causing a compile-time error.



Given Data / Assumptions:

  • Super has only Super(String) and no zero-argument constructor.
  • Sub extends Super and defines Sub(String) without calling super(text).
  • Java automatically tries to insert super() if not provided.


Concept / Approach:
Because Super lacks a no-arg constructor, the implicit super() in Sub’s constructor is invalid. The compiler emits an error such as "constructor Super in class Super cannot be applied to given types". Therefore, the code does not compile, and no runtime behavior is observed.



Step-by-Step Solution:

Parse Sub(String) and note absence of a call to super(...).Compiler inserts super().Check Super: only Super(String) exists → mismatch.Compilation fails with an explanatory diagnostic.


Verification / Alternative check:
Fix by writing Sub(String text) { super(text); i = 2; } which compiles and prints 2.



Why Other Options Are Wrong:

  • Any numeric output assumes successful compilation and object construction.
  • Runtime exception: The program never runs.


Common Pitfalls:
Forgetting to chain to an available superclass constructor; assuming a hidden no-arg constructor exists even when another constructor is declared explicitly.



Final Answer:
Compilation fails.

Discussion & Comments

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