Methods With Same Name as Constructor - Why?
Solution 1:
My guess is that it's allowed because explicitly disallowing it would add another requirement to Java's identifier naming rules for very little benefit. Unlike, say, C++, Java always requires that constructors are called with the new
keyword, so there's never any ambiguity about whether an identifier refers to a method or a constructor. I do agree that a method with the same name as its parent class is quite confusing at first glance, and it should be almost certainly be avoided. That said, I'm glad they chose not to further complicate the language by banning such methods.
Solution 2:
This is heinous. I would not allow such a thing to survive a code review.
Solution 3:
The only valid reason - that I can think of - for utilizing this is if the parent class adds methods after you have written the child class:
interface Father { } // version 1.0
class Son implements Father { Son ( ) { } } // version 1.0
interface Father { void Son ( ) ; /* new method */ } // version 2.0
class Son implements Father { Son ( ) { } void Son ( ) { } } // version 2.0
If you have no control of the Father
interface, but do have control of the Son
class, then you have to change Son
somehow. You could
- Change the name of the
Son
class - Break the relationship with the
Father
class - Add the
Son
method
If the Son
class is a dependency of many other projects then #1 and #2 may be unacceptable, leaving you with no choice but to add the Son( )
method.
This is a highly contrived example. You should never see such a thing in real code.
Solution 4:
The constructor has the same name as the class and falls under the Type namespace. Method namespace is distinct from Type namespace in Java. So this is technically allowed (and this is not overloading).
However, there isn't ANY valid reason to actually name a method the same as the class name. It will be considered as a very bad practice.