1.2.14 Defining a Field Whose Type Is Another Class

A Class Can Contain a Reference to Another Custom Type

Suppose the program defines:

C#
class Team
{
    public string name;
}

A Player can have a field whose type is Team:

C#
class Player
{
    public string name;
    public Team team;
}

The team field can hold a reference to a Team object.

The Field Declaration Does Not Create the Related Object

After:

C#
Player player1 = new Player();

the team reference field may still be:

Plain text
null

You still need a Team object:

C#
Team team1 = new Team();

and a relationship assignment:

C#
player1.team = team1;

Connect the Field to UML

Class diagram:

Plain text
Player
-------------------------
name : string
team : Team

Object diagram:

Plain text
player1 : Player -------- team1 : Team

C# field:

C#
public Team team;

C# reference assignment:

C#
player1.team = team1;

Those representations describe related aspects of the same design.

Use the Custom Type, Not a Description of the Object

This:

C#
public Team team;

stores a Team reference.

This:

C#
public string team;

stores text.

If the model requires an object relationship, use the compatible class type rather than replacing the relationship with a name string.

Class Relationships Begin with Type Design

Before two runtime objects can be connected through a field, the class must define a place for that reference.

That is why class design comes before object relationship assignment.