CHAPTER 5 UNDERSTANDING ENCAPSULATION
public int currSpeed;
// A custom default constructor.
public Car()
{
petName = "Chuck";
currSpeed = 10;
}
// Here, currSpeed will receive the
// default value of an int (zero).
public Car(string pn)
{
petName = pn;
}
// Let caller set the full state of the Car.
public Car(string pn, int cs)
{
petName = pn;
currSpeed = cs;
}
...
}
Keep in mind that what makes one constructor different from another (in the eyes of the C#
compiler) is the number of and type of constructor arguments. Recall from Chapter 4, when you define a
method of the same name that differs by the number or type of arguments, you have overloaded the
method. Thus, the Car class has overloaded the constructor to provide a number of ways to create an
object at the time of declaration. In any case, you are now able to create Car objects using any of the
public constructors. For example:
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Class Types *****\n");
// Make a Car called Chuck going 10 MPH.
Car chuck = new Car();
chuck.PrintState();
// Make a Car called Mary going 0 MPH.
Car mary = new Car("Mary");
mary.PrintState();
// Make a Car called Daisy going 75 MPH.
Car daisy = new Car("Daisy", 75);
daisy.PrintState();
...
}
168