A Team can receive an existing Player as captain. Passing a reference connects objects without constructing another Player.
Use the name-and-jersey Player definition from the parameterized-constructor lesson.
public class Team
{
private Player captain;
public Team(Player captain)
{
this.captain = captain;
}
public string GetCaptainName()
{
return this.captain.GetName();
}
}This example requires a non-null captain. The constructor stores the reference; GetCaptainName asks that Player for its name. The example does not validate null, so callers must satisfy the stated assumption.
Player jordan = new Player("Jordan", 7);
Team wildcats = new Team(jordan);
string captainName = wildcats.GetCaptainName();captainName is Jordan. Only the first line creates a Player. Team construction creates a Team and copies the supplied Player reference into its field.