2.5.13 Defining Private Fields That Reference Objects

Defining Private Fields That Reference Objects

Team can store a reference to its captain privately. Hiding the reference does not copy the Player or make that Player immutable.

Retain a supplied object

Use the controlled-access Player from the linked lesson.

Soccer example
public class Team
{
    private Player captain;

    public void ChooseCaptain(Player player)
    {

        if (player != null)
        {
            this.captain = player;
        }
    }

    public bool RecordCaptainTurn()
    {

        if (this.captain == null)
        {
            return false;
        }

        return this.captain.RecordTurn();
    }
}

Before selection, captain is null. The null check returns false before attempting a method call. ChooseCaptain stores the supplied reference, so Team and the caller can reach the same Player.

Follow shared state
Caller method
Player jordan = new Player();
Team wildcats = new Team();
wildcats.ChooseCaptain(jordan);
bool accepted = wildcats.RecordCaptainTurn();
int turns = jordan.GetNumberOfTurns();

accepted is true and turns is 1. No second Player was created during selection. Private prevents outside access through Team.captain, but the original jordan variable still has access to Player public methods.

The caller jordan reference and the private captain reference of wildcats both reach the same Player with one turn.
Two routes reach the same Player
Apply the idea
Check your understanding