Why is the following allowed:
public class Foo {
public Foo() { ... }
public void Foo() { ... }
}
Is there ever a valid reason for naming a method the same as the class?
Why is the following allowed:
public class Foo {
public Foo() { ... }
public void Foo() { ... }
}
Is there ever a valid reason for naming a method the same as the class?
This is heinous. I would not allow such a thing to survive a code review.
The method's return value is defined as void, whereas the constructor has no return value, which makes them different and thus valid code. Why someone would want to do that, however, is beyond me.
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.
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.
I cannot see a valid reason for it.
C# provides a compiler error - "Member Names Cannot Be The Same As Their Enclosing Type"
It could be quite confusing, especially when using reflection to look at the composition of an object.
The only valid reason - that I can think of - for utilzing 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 class, but do have control of the Son class, then you have to change Son somehow. You could
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.