Inheritance in Object Oriented Programming
It’s a kind of relationship between two classes which allows one class to inherit code from the other. It represents “is-a” relationship. For e.g. a car is a vehicle. To implement inheritance, one class must inherit or extend behaviors of another class. When we say extend, we mean that a class might support two functionalities for example and another class can inherit from it and then provide some new functionalities thus this new class comprises of old and new.
Note: Examples of this and its related articles are related to high level statically typed object oriented languages such as C# and Java.
Key points
- The class that is being inherited is called base or parent class.
- The class that’s inheriting base class is called derived or child class.
- In C#, if you want to prevent a class from being inherited then use sealed keyword in class declaration.
- In C#, even when we don’t specify any class as base class, the class would inherit from the ultimate base class called Object class.
Types of inheritance
- Single-level inheritance
- Multi-level inheritance
- Multiple inheritances with interfaces
Implement — using class — single level
Implement — using class — multi level
Implement — using interfaces
Conceptual Aside — multiple inheritances
C# doesn’t support multiple inheritances with classes because of the diamond problem. Because if a class inherits from two base classes that have a method with same signature then compiler wouldn’t know which implementation needs to be execute. But interfaces don’t contain implementation of methods so it’s up to the derived class to provide implementation.
Advantages
- Code reusability
- Polymorphic behavior
Thank you for reading this article. I hope this and its related articles will help you start your programming journey.
References:
Disclaimer & fair use statement:
This website may contain copyrighted material, the use of which may not have been specifically authorized by the copyright owner. This material is available in an effort to explain issues relevant to the Digital Humanities and foreign language education (e.g. historical, environmental, political, scientific, etc. ) or to illustrate the use and benefits of an educational tool. The material contained in this website is distributed without profit for research and educational purposes. Only small portions of the original work are being used and those could not be used easily to duplicate the original work. This should constitute a ‘fair use’ of any such copyrighted material (referenced
and provided for in section 107 of the US Copyright Law). If you wish to use any copyrighted material from this site for purposes of your own that go beyond ‘fair use’, you must obtain expressed permission from the copyright owner.