Team can store a reference to its captain privately. Hiding the reference does not copy the Player or make that Player immutable.
Use the controlled-access Player from the linked lesson.
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.
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.