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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
newkeyword, 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.