Java inheritance and constructors — what exact output is printed?\n\nclass Base\n{ \n Base()\n {\n System.out.print("Base");\n }\n}\npublic class Alpha extends Base\n{ \n public static void main(String[] args)\n { \n new Alpha(); // Line 12\n new Base(); // Line 13\n }\n}\n\nPredict the combined standard output produced by running main().

Difficulty: Easy

Correct Answer: BaseBase

Explanation:


Introduction / Context:
This question checks your understanding of Java constructor chaining during inheritance and the effect of creating instances on standard output. The subclass Alpha does not declare a constructor, so the compiler provides a default no-argument constructor that implicitly invokes super().



Given Data / Assumptions:

  • class Base defines a no-argument constructor that prints "Base".
  • class Alpha extends Base and has no explicit constructor.
  • main creates a new Alpha, then a new Base, in that order.
  • No package–visibility complications are introduced; both classes are in the same compilation unit for the purpose of this MCQ.


Concept / Approach:
When a class has no explicitly declared constructor, Java provides a default constructor that calls super(). Therefore, new Alpha() first constructs its Base subobject by invoking Base(), which prints "Base". Alpha itself does not print anything. The second expression new Base() again calls Base(), printing "Base" a second time. Standard output is simply the concatenation of those prints, with no newline characters added by this code.



Step-by-Step Solution:

Call new Alpha(): implicit super() → Base() prints "Base".Alpha’s default constructor prints nothing.Call new Base(): Base() prints "Base" again.Total output becomes "BaseBase".


Verification / Alternative check:
If Alpha had its own constructor printing, the output would include that text too. As written, only Base prints.



Why Other Options Are Wrong:

  • "Base": ignores the second instantiation of Base.
  • "Compilation fails": nothing illegal in the code.
  • "No output": contradicted by Base’s print statements.


Common Pitfalls:
Forgetting the implicit super() call in the compiler-provided default constructor.



Final Answer:
BaseBase

Discussion & Comments

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