2.6.5 Parameterized Constructors

Video: This, Revisited (11:09)
Parameterized Constructors

Construct Jordan and Casey with different starting information through the same Player constructor. Parameters give each new instance its own values.

Assign inputs into the new object
Soccer example
public class Player
{
    private string name;
    private int jerseyNumber;

    public Player(string name, int jerseyNumber)
    {
        this.name = name;
        this.jerseyNumber = jerseyNumber;
    }

    public string GetName()
    {
        return this.name;
    }

    public int GetJerseyNumber()
    {
        return this.jerseyNumber;
    }
}

The constructor name exactly matches Player and has no return type. In this.name = name, the left side is the new object field; the right side is the parameter. Writing name = name would only assign the parameter to itself.

Match arguments by position and type

Place these statements inside an outside method.

Create two independent players
Player jordan = new Player("Jordan", 7);
Player casey = new Player("Casey", 12);
string name = jordan.GetName();
int jersey = casey.GetJerseyNumber();
After both creation expressions
Reference Stored name Stored jersey
jordan Jordan 7
casey Casey 12

name receives Jordan and jersey receives 12. Each new expression creates one object and runs its constructor for that object. The parameter names do not become variables available to the outside caller.

Keep initialization claims precise
Apply the idea
Check your understanding