Introduction to inheritance
So far, the Animal
class does a fine job of providing a way to differentiate between different types of animals. However, not all animals will have the same characteristics. A cat will not have gills, so having an Animal
class have a property named NumberOfGills
would be a waste of space for any animal that is not a reptile or sea creature. However, we know that all the animals will have an age, color, and type. Can we make a new animal with unique properties? Could we do it without having to recreate the Animal
class again, which already contains members that could be used?
Inheritance enables the reuse of classes to create new classes that generate objects with modified members. Classes that inherit properties and methods from another class are called derived, or child, classes, while the original class is called a base or parent class. The following figure shows how to implement inheritance in C# with a base and derived class: