Java constructors vs. methods with the class name: will a method declared as "void A()" act as a constructor?\n\npublic class A {\n void A() { // not a constructor due to return type\n System.out.println("Class A");\n }\n public static void main(String[] args) {\n new A();\n }\n}

Difficulty: Easy

Correct Answer: The code executes with no output.

Explanation:


Introduction / Context:
This checks whether you can distinguish a true Java constructor from a method that merely shares the class name. A constructor has no return type, not even void. If a return type is present, the member is a regular method and will not be invoked by object creation unless called explicitly.



Given Data / Assumptions:

  • Class A declares void A() { System.out.println("Class A"); }.
  • No explicit constructor is declared.
  • main executes new A().


Concept / Approach:
Because void A() has a return type, it is not a constructor. The compiler synthesizes a default no-argument constructor A() that does nothing. Therefore, new A() calls this implicit constructor, not the method, resulting in no output.



Step-by-Step Solution:

Parse declarations: method named A with return type void.No user-defined constructor → default constructor is provided.new A() invokes the default constructor, which has an empty body.Program terminates without printing.


Verification / Alternative check:
Remove the return type: change "void A()" to "A()". Then new A() would print "Class A".



Why Other Options Are Wrong:

  • Class A: Would require the method to be a real constructor or to be called explicitly.
  • Compilation fails / exception: The code is valid and runs.


Common Pitfalls:
Assuming any member with the class name is a constructor; forgetting that a return type disqualifies it as such.



Final Answer:
The code executes with no output.

More Questions from Declarations and Access Control

Discussion & Comments

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