Free mag vol1 | Page 277

CHAPTER 6  UNDERSTANDING INHERITANCE AND POLYMORPHISM public int Speed { get { return currSpeed; } set { currSpeed = value; if (currSpeed > maxSpeed) { currSpeed = maxSpeed; } } } } Notice that the Car class is making use of encapsulation services to control access to the private currSpeed field using a public property named Speed. At this point, you can exercise your Car type as follows: static void Main(string[] args) { Console.WriteLine("***** Basic Inheritance *****\n"); // Make a Car object and set max speed. Car myCar = new Car(80); // Set the current speed, and print it. myCar.Speed = 50; Console.WriteLine("My car is going {0} MPH", myCar.Speed); Console.ReadLine(); } Specifying the Parent Class of an Existing Class Now assume you want to build a new class named MiniVan. Like a basic Car, you want to define the MiniVan class to support data for a maximum speed, current speed, and a property named Speed to allow the object user to modify the object’s state. Clearly, the Car and MiniVan classes are related; in fact, it can be said that a MiniVan “is-a” type of Car. The “is-a” relationship (formally termed classical inheritance) allows you to build new class definitions that extend the functionality of an existing class. The existing class that will serve as the basis for the new class is termed a base or parent class. The role of a base class is to define all the common data and members for the classes that extend it. The extending classes are formally termed derived or child classes. In C#, you make use of the colon operator on the class definition to establish an “is-a” relationship between classes. Assume you have authored the following new MiniVan class: // MiniVan "is-a" Car. class MiniVan : Car { } Currently, this new class has not defined any members whatsoever. So, what have you gained by extending your MiniVan from the Car base class? Simply put, MiniVan objects now have access to each public member defined within the parent class. 214