This might be obvious but how come the machine can create 50k objects all called cat. Would it not need a different name for each object in order for them to exist as references.
Daniel Whyte
Level 17
Cat cat = newCat;
Under discussion
Comments (1)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
23 January 2021, 14:53useful
The machines is creating 50,000 objects that get set to the variable name cat, not 50,000 objects all called cat. A variables is no more than a way to access, or reference, an object. When you create an object and set it to a variable you are able to access that object using that variable. When you set an object to a variable that already has an object, the variable loses its reference to the old object and will then reference the new object. The old object will remain in memory for a time, but will soon be destroyed. That is how the garbage collector in Java works, by removing any objects that are no longer referenced.
That may or may not make sense, here is an analogy: It would be like having 1 cup and filling it full with water 50,000 times. All 50,000 refills wouldn't exist in that one cup, only the very last refill would exist. Java's "garbage collector" could be thought of as the person that came around from time to time and had to clean the 49,999 cups of water that were all over the floor.
+2