2.6.7 Passing Objects to Constructors

Passing Objects to Constructors

A Team can receive an existing Player as captain. Passing a reference connects objects without constructing another Player.

Store the supplied reference

Use the name-and-jersey Player definition from the parameterized-constructor lesson.

Soccer example
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.

Distinguish a copied reference from a copied object
Caller method
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.

Team has a private captain reference to Player and receives that reference through its constructor; the field is represented only on the association.
Team retains a reference to an existing Player
Apply the idea
Check your understanding