Team receives its captain but creates its own roster list. That keeps list allocation and the initial captain registration inside the class that manages the roster.
Use the Player from the parameterized-constructor lesson and supply a non-null captain.
using System.Collections.Generic;
public class Team
{
private Player captain;
private List<Player> players;
public Team(Player captain)
{
this.captain = captain;
this.players = new List<Player>();
this.players.Add(captain);
}
public int GetPlayerCount()
{
return this.players.Count;
}
}The list field initially contains null. The constructor must create the list before calling Add. The Add call stores the same Player reference supplied as captain.
Player jordan = new Player("Jordan", 7);
Team wildcats = new Team(jordan);
int count = wildcats.GetPlayerCount();| Type | Number |
|---|---|
| Player | 1 |
| Team | 1 |
| List of Player references | 1 |
count is 1. Neither assigning captain nor adding that reference to the list creates a second Player.