简体   繁体   中英

Creating two objects with same name in Java

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.

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

In the above example you have two different object references namely planet1 and planet2.

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

Here you have only one object reference planet1 that's accessible. When the second line is executed the reference of the first object is no longer available since it has been over written with the second object's reference.

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.

The way you approached object instantiation creates two variables (planet1 and planet2) with references to two distinct Planet objects. These objects can be accessed by other operations.

The instructor's approach first instantiates a Planet object referenced by the variable planet1. Then the reference is discarded, and set to point to a newly constructed Planet object. In this case, only the planet with low temperature and ice is accessible. The previous Planet object with high temperature and No water can no longer be accessed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM