How is Inheritance achieved in C#?Inheritance
is where you have a generalized class whose behavior is extended in specialized
class.
For example, there are different shapes namely square, rectangle, octagon and many others. All of them have common characteristics of a shape, for example Area. You can compute area of any shape but each shape has its own formula for computing area. Such common characteristics will be captured in the class shape which will then be inherited by specialized classes like square and rectangle. There are different types of inheritance. They are pictorially represented with real time examples in the diagram shown above. Apart from the simple inheritance, hierarchical inheritance, multiple inheritance and multilevel inheritance, you can also have a hybrid situation wherein you have more than one type of inheritance jumbled together. In C#, you achieve multiple inheritance using interface. All other types of inheritance can be achieved by extending base class in derived class. Interface is a separate feature on its own. Hence this article will cover simple inheritance, hierarchical inheritance and multilevel inheritance. Given below are examples of each type of inheritance implemented using C#: Example for Simple Inheritance and Hierarchical Inheritance: class sampleShape
{ Output of this code will be: Area of Rectangle:200, Area of Triangle:100 Here sampleRectangle derives from sampleShape, this demonstrates simple inheritance. However, sampleTriangle also inherits from sampleShape and both the derived classes override area method to implement the corresponding formula. This demonstrates hierarchical inheritance. Multilevel Inheritance: Multilevel inheritance is where base class is derived by the derived class. And the derived class is inherited further by next level of derived class. And this leveling might continue for any level based on your requirement. Here is an example to demonstrate multilevel inheritance: class baseClass
{ class testClass
{ Output of this code will be: Executing
baseClass method
Note that
derived class can access and override methods of all its parents in the
hierarchy and not just its immediate base class.
|