CHAPTER 5 UNDERSTANDING ENCAPSULATION
// Constructors.
public Motorcycle() { }
public Motorcycle(int intensity)
{
SetIntensity(intensity);
}
public Motorcycle(int intensity, string name)
{
SetIntensity(intensity);
driverName = name;
}
public void SetIntensity(int intensity)
{
if (intensity > 10)
{
intensity = 10;
}
driverIntensity = intensity;
}
...
}
A cleaner approach is to designate the constructor that takes the greatest number of arguments as
the “master constructor” and have its implementation perform the required validation logic. The
remaining constructors can make use of the this keyword to forward the incoming arguments to the
master constructor and provide any additional parameters as necessary. In this way, you only need to
worry about maintaining a single constructor for the entire class, while the remaining constructors are
basically empty.
Here is the final iteration of the Motorcycle class (with one additional constructor for the sake of
illustration). When chaining constructors, note how the this keyword is “dangling” off the constructor’s
declaration (via a colon operator) outside the scope of the constructor itself:
class Motorcycle
{
public int driverIntensity;
public string driverName;
// Constructor ch