CHAPTER 6 UNDERSTANDING INHERITANCE AND POLYMORPHISM
Note Although constructors are typically defined as public, a derived class never inherits the constructors of a
parent class. Constructors are only used to construct the class that they are defined within.
Given the relation between these two class types, you could now make use of the MiniVan class like
so:
static void Main(string[] args)
{
Console.WriteLine("***** Basic Inheritance *****\n");
...
// Now make a MiniVan object.
MiniVan myVan = new MiniVan();
myVan.Speed = 10;
Console.WriteLine("My van is going {0} MPH",
myVan.Speed);
Console.ReadLine();
}
Again, notice that although you have not added any members to the MiniVan class, you have direct
access to the public Speed property of your parent class, and have thus reused code. This is a far better
approach than creating a MiniVan class that has the exact same members as Car, such as a Speed
property. If you did duplicate code between these two classes, you would need to now maintain two
bodies of code, which is certainly a poor use of your time.
Always remember, that inheritance preserves encapsulation; therefore, the following code results in
a compiler error, as private members can never be accessed from an object reference.
static void Main(string[] args)
{
Console.WriteLine("***** Basic Inheritance *****\n");
...
// Make a MiniVan object.
MiniVan myVan = new MiniVan();
myVan.Speed = 10;
Console.WriteLine("My van is going {0} MPH",
myVan.Speed);
// Error! Can't access private members!
myVan.currSpeed = 55;
Console.ReadLine();
}
On a related note, if the MiniVan defined its own set of members, it would still not be able to access
any private member of the Car base class. Remember, private members can only be accessed by the class
that defines it. For example, the following method in MiniVan would result in a compiler error:
// MiniVan derives from Car.
class MiniVan : Car
{
public voi d TestMethod()
{
215