1.6.16 Changing an Object Through a Shared Reference

Two Paths Can Reach One Field

If `first` and `current` refer to the same Player, both paths reach the same `NumberOfTurns` field. The field belongs to the Player object.

First and current refer to the Player whose turn count is one.
Initial relationship
  • New
  • Changed
  • Removed
An Increment Changes the Shared Object

Suppose the Player starts with zero turns:

Player current = first;
current.NumberOfTurns++;

After the increment, `first.NumberOfTurns` is `1`. Both variables reach the Player whose field was changed.

The Variable Does Not Own the Field

There are two reference variables, but only one Player and one `NumberOfTurns` field. The value is not copied into `first` and `current` separately.

Reassignment Separates the Paths

Now `current` can receive a new Player:

current = new Player();
current.NumberOfTurns = 5;

`first.NumberOfTurns` remains `1`; `current.NumberOfTurns` is `5`. Each variable now reaches a different object.

After reassignment the references lead to different Players and turn counts.
How the relationship changes
  • New
  • Changed
  • Removed