Free mag vol1 | Page 276

CHAPTER 6 Understanding Inheritance and Polymorphism Chapter 5 examined the first pillar of OOP: encapsulation. At that time, you learned how to build a single well-defined class type with constructors and various members (constructors, fields, properties, methods, constants, and read-only fields). This chapter will focus on the remaining two pillars of OOP: inheritance and polymorphism. First, you will learn how to build families of related classes using inheritance. As you will see, this form of code reuse allows you to define common functionality in a parent class that can be leveraged, and possibly altered, by child classes. Along the way, you will learn how to establish a polymorphic interface into class hierarchies using virtual and abstract members, as well as the role of explicit casting. We’ll wrap up by examining the role of the ultimate parent class in the .NET base class libraries: System.Object. The Basic Mechanics of Inheritance Recall from Chapter 5 that inheritance is the aspect of OOP that facilitates code reuse. Specifically speaking, code reuse comes in two flavors: inheritance (the “is-a” relationship) and the containment/delegation model (the “has-a” relationship). Let’s begin this chapter by examining the classical inheritance model of the “is-a” relationship. When you establish “is-a” relationships between classes, you are building a dependency between two or more class types. The basic idea behind classical inheritance is that new classes can be created using existing classes as a starting point. To begin with a very simple example, create a new Console Application project named BasicInheritance. Now assume you have designed a class named Car that models some basic details of an automobile: // A simple base class. class Car { public readonly int maxSpeed; private int currSpeed; public Car(int max) { maxSpeed = max; } public Car() { maxSpeed = 55; } 213