Construct Jordan and Casey with different starting information through the same Player constructor. Parameters give each new instance its own values.
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.
Place these statements inside an outside method.
Player jordan = new Player("Jordan", 7);
Player casey = new Player("Casey", 12);
string name = jordan.GetName();
int jersey = casey.GetJerseyNumber();| 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.