Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Methods With Same Name as Constructor - Why?

Tags:

java

oop

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?

like image 914
Tom Tresansky Avatar asked Aug 03 '10 23:08

Tom Tresansky


People also ask

Can you have a method with same name as constructor?

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.

Why must a constructor have the same name?

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.

What is it called when methods are used with the same name?

The practice of defining more than one method in a class with same name is called method overloading.

Can the constructor only have the same name of the class?

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.


2 Answers

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.

like image 114
bcat Avatar answered Oct 14 '22 21:10

bcat


This is heinous. I would not allow such a thing to survive a code review.

like image 21
duffymo Avatar answered Oct 14 '22 22:10

duffymo