Creating two objects with same name in Java

Tags:



I have a class name Planet and I am making objects in main.

Planet planet1 = new Planet("High Temperature","No Water);
Planet planet2 = new Planet("Low Temperature","Ice");

However, I saw my instructor doing this:

Planet planet1 = new Planet("High Temperature","No Water);
       planet1 = new Planet("Low Temperature","Ice");

So basically, my instructor is also creating two objects. I understand that a new object is basically formed when constructor is called but I always thought that the two objects need to have distinct names as well.

As you can see above, there are two objects created using the name planet1.

Also, is there any difference in creating two objects with the two different ways mentioned above.

Answer

In both cases, you are creating two distinct instances of the Planet class. In the second case, you assign your high-temperature planet to the variable planet1, and then create a new planet (low temperature), assigning it to the same variable (planet1), discarding a reference to your earlier high-temperature planet. Java’s garbage collector, realizing that this first planet is no longer reachable, deletes it from the heap, reclaiming its memory.

In the first case, you have two distinct Planet objects and two distinct variables of type Planet, each storing a reference to one of the two objects.



Source: stackoverflow