C# 7 and .NET Core 2.0 Blueprints
上QQ阅读APP看书,第一时间看更新

Inheritance

The ability to be able to create your own classes that reuse, extend, and modify the behavior that the base class defines is called inheritance. Another important aspect to understand is that a derived class can only directly inherit a single base class.

Does this then mean that you can only inherit the behavior defined in a single base class? Well, yes and no. Inheritance is transitive in nature.

To explain this, imagine that you have three classes:

  • Person
  • Pedestrian
  • Driver

The Person class is the base class. Pedestrian inherits from the Person class and therefore Pedestrian inherits the members declared in the Person class. The Driver class inherits from the Pedestrian class and therefore Driver inherits the members declared in Pedestrian and Person:

This is what is meant when we say that inheritance is transitive. You can only inherit from a single class, but you get all the members that the class you inherit from, inherits itself. You can only inherit from a single class, but you get all the members that the class you are inheriting from, inherits from its base class. Put another way, the Driver class can only inherit from a single base class (in the preceding image, the Pedestrian class). This means that because the Pedestrian class inherits from the Person class, and the Driver class inherits from the Pedestrian class, that the Driver class also inherits the members in the Person class.