Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating objects with same name as class in java

In C++ when I create an object like the following, then no more objects can be created for the same class.

Box Box; //Box is the class Name

Here Box becomes an object and whenever we use Box again the compiler recognizes it as an object. But in the case of java this isn't.

Box Box = new Box(); 
Box box = new Box(); //valid 

What is the reason behind this?

like image 824
Tamil Maran Avatar asked Dec 23 '14 10:12

Tamil Maran


People also ask

Can object have same name as class in Java?

We can have a method name same as a class name in Java but it is not a good practice to do so.

Can an object have the same name as the class?

An object with the same name as a class is called a companion object. Conversely, the class is the object's companion class.

Can we create objects with same name?

To answer your original question, you can't have two objects of the same or similar types (e.g., two tables, or a table and a view) with the same name in the same schema.

Can I create a method with the same name as a class name?

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.


1 Answers

Basically, Java has slightly different set of syntax rules, by the sounds of it. When the grammar says you've got a variable declaration with an initializer, such as this:

Box box = new Box();

... it knows that Box has to be the name of a type, not the name of a variable. So it doesn't matter whether or not there's a variable called Box in scope. (That applies to the new operator as well.)

I don't know the intimate details of the C++ syntax, but it sounds like it's not set up to make that distinction, at least in the example you've given. It's not like it's a feature as such - it's just a matter of how names are looked up by the compiler.

like image 163
Jon Skeet Avatar answered Nov 08 '22 07:11

Jon Skeet