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?
Yes, It is allowed to define a method with the same name as that of a class. There is no compile-time or runtime error will occur. But this is not recommended as per coding standards in Java. Normally the constructor name and class name always the same in Java.
Every class object is created using the same new keyword, so it must have information about the class to which it must create an object. For this reason, the constructor name should be the same as the class name.
The practice of defining more than one method in a class with same name is called method overloading.
Yes, the constructor should always have the same name as the class. Constructor looks like method but it is not. It does not have a return type and its name is same as the class name. Mostly it is used to instantiate the instance variables of a class.
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.
This is heinous. I would not allow such a thing to survive a code review.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With