Next: None. Up: Using objects. Previous: Putting it together.


References

Textbook: Section 3.7

There's an important detail about objects that makes objects very unlike the primitive types. In a primitive type, when you move a value, a copy of the value is placed in memory. So if the memory looks like this:

   a: 45    b: 23
And then I do ``a=b;,'' the memory would change to the following.
   a: 23    b: 23
Now, if I alter a again (maybe with ``a=5;''), the value of b is unchanged.
   a: 5     b: 23

Object's don't work that way: A variable holding an object only refers to a specific, individual object in the world. We would say that the variable points to the object. Say we execute the following.

Graphics blue_g = window.getGraphics();
Graphics green_g = blue_g;
Here, we've created a variable blue_g that refers to a specific Graphics object. In the next line, I made green_g also refer to that same object. They are both pointing to the same location in memory, where the graphics data is stored.

This distinction turns out to be very important. Suppose we do the following.

blue_g.setColor(Color.blue);
green_g.setColor(Color.green);
You may think this sets the colors so that I can use blue_g to draw blue things and green_g to draw green things. But in fact, since both are pointing to the same instance, both setColor methods are being called on the same instance. As a result, after both statements occur, that single instance is thinking that green is the current color. Say we now try to draw a circle using blue_g.
blue_g.fillOval(80, 80, 40, 40);
This would actually draw a green circle!

We say that an object variable is actually a reference to the actual object in memory. This distinction of objects as references is pervasive throughout Java. Object parameters are passed by reference, so that changes to a parameter object's fields within the method affect the object's fields outside the method.

In this case, the solution is simple: Don't make both blue_g and green_g refer to the same object. Instead, create two separate Graphics objects.

Graphics blue_g = window.getGraphics();
Graphics green_g = window.getGraphics();

There's a special reference that's worth noting, called the null object. You use this when you want to denote that a variable no longer refers to a valid object.

blue_j = null;
When a variable is null, then you can't use it - it's effectively pointing to nothing at all, so attempts to access it result in crashing your program. Setting a variable to null is useful as a placeholder when you want to remember that something doesn't exist; we'll see examples of its use later.


Next: None. Up: Using objects. Previous: Putting it together.