2.3.8 How to Reuse Variables

Variables can be used over and over again to reference instances of objects. Once they are assigned to again the previous reference will no longer exists, but the object it was references could possibly continue to exist.

For example, let's look at how we add objects to a list.

As of line 82 there is a List of Food items that has been instantiated and a single Food object in memory.

However, once we execute line 82 the reference to the first Food object will no longer exist and a new one will be formed.

We don't want just to "blow away" the Cheetah Chips object, though. To re-use a variable but keep the old object around we will need to make a reference to it. In this case we will add the Cheetah Chips to the list of Food.

Now when we execute line 84 the reference to the food variable goes away, but the object still exists in the List of Food.