2.1.9 How to Assign Null and Use Local References

Assigning null to an object has a number of nuances. If assigning null to an object that has no other references, the object will no longer exist in memory. If, however, there is a prior reference to that object and an object is assigned null, the prior reference will continue to be assigned that object.

For example, the Zoo has discovered that the Boss of the park, Michael, has been making other Employees feel uncomfortable with off-color jokes. They have reached an agreement with Michael and he will take a role as a Custodian for a lower wage.


As of line 40...

...the object diagram would look like this:

So let's fire Michael from his position as Boss by assigning Boss to null.

This will make the object diagram look like this:

Since there are no other references to Michael, he will just leave the Zoo entirely. But we didn't want to just fire Michael we wanted to put him in a new position. So instead let's give him the Custodian role before removing him from his role as Boss.

So when line 42 is executed...

the object diagram looks like this:

The Boss field and the Custodian field both reference the same object.


So if we execute line 43...

...both the Boss's Wage and the Custodian's Wage change to 9.00

But we don't want Michael being the Boss anymore just the Custodian. So now let's assign the Boss field to null.


When line 45 executes, the Boss will be null, but the Custodian will still be an instance of Michael.

In an object diagram it will look like this:

The Boss field is null, but because there was another reference to Michael, he stays in the Zoo.