Chapter 11. Inheritance and Polymorphism

In Chapter 6, we explained how classes derive from one another and described how classes can inherit properties and methods from their parent classes. In Chapter 7, you learned how to create your own classes and use objects of those classes, but you didn’t see how the inheritance aspect works in practice. That’s about to change.

We mentioned in Chapter 6 that the three key principles of object-oriented programming are encapsulation (discussed in Chapter 7), specialization, and polymorphism. This chapter focuses on specialization, which is implemented in C# through inheritance. You’ll see how to create your own class hierarchy, and how to enforce that child classes implement the methods of their parent classes. You’ll even see how to create completely abstract classes, and why you’d want to. You can’t create an instance of an abstract class; you can only inherit from it. This chapter also explains how instances of a child class can be treated as though they were instances of one of the child class’s ancestor classes, a process known as polymorphism. This chapter ends with a consideration of sealed classes, which cannot be specialized, and a discussion of the root of all classes, the Object class.

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.