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?

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow