2.6.1 Why Classes Use Constructors

Video: Constructors (31:16)
Why Classes Use Constructors

Creating a Player and then setting several public fields leaves the caller responsible for remembering every setup step. A constructor can establish required starting information during creation.

Notice the gap between creation and setup
Old public-field setup
Player jordan = new Player();
jordan.Name = "Jordan";
jordan.JerseyNumber = 7;

This old Player design exposes Name and JerseyNumber as fields. Immediately after new Player finishes, those fields have default values unless initializers supply others. Forgetting a later assignment can leave the player incompletely configured.

Supply required information at creation

A constructor is a special declaration with the class name and no return type. It executes as part of creating a new instance.

Desired creation call
Player jordan = new Player("Jordan", 7);

The call supplies two arguments. The constructor will receive them as parameters and initialize the new Player before the expression finishes. This line illustrates the creation contract; the complete class is developed in the constructor lessons.

Separate initialization from later actions
Different jobs
Operation Purpose
Constructor Establish starting state of a new object
RecordTurn Request a later change to an existing object
GetNumberOfTurns Read current state of an existing object

Constructors also decide which objects to create internally and which existing references to retain. Those choices become important when Team connects its captain and roster.

Apply the idea
Check your understanding