What is inheritance? Explain different types of inheritance.
Acquiring (taking) the properties of one class into another class is called inheritance. Inheritance provides reusability by allowing us to extend an existing class.
The reason behind OOP programming is to promote the reusability of code and to reduce complexity in code and it is possible by using inheritance.
C# does not support multiple inheritances of classes, the same thing can be done using interfaces.
Private members are not accessed in a derived class when one class is derived from another.
The following are the types of inheritance in C#.
The inheritance concept is based on a base class and derived class.
Single inheritance
It is the type of inheritance in which there is one base class and one derived class.
For example,
In the preceding sample program Accountcreditinfo is the base class and debitinfo is the derived class.
This is the type of inheritance in which there are multiple classes derived from one base class. This type of inheritance is used when there is a requirement of one class feature that is needed in multiple classes.
For example,
In the preceding program one base class is derived in many classes hence it is a called a Hierarchical Inheritance.
Multilevel inheritance
When one class is derived from another derived class then this type of inheritance is called multilevel inheritance.
For example,
In the preceding program, each class is derived from one class that is derived from another class hence this type of inheritance is called Multilevel Inheritance.
Multiple inheritance using Interfaces
C# does not support multiple inheritances of classes. To overcome this problem we can use interfaces.
For example,
In the preceding program the ICar class inherits the features of the two interfaces hence this type of inheritance is called Multiple Inheritance.