One of the major benefits of object-oriented programming is code reuse. Programmers develop lot of code over time. If this code can be reused, they can save time and effort in developing and testing a new project. In structured programming, if the code is arranged in appropriate independent functions, it can be reused in future applications. For object-oriented programming, the inheritance feature helps us to achieve code reuse. It help us to write classes that extend the functionality of classes that already exist. We generally do so because we have already developed a few classes and we want to add some functionality to them without breaking the existing code or rewriting them entirely again. In some situations, we may even like to reuse the code developed by others and add more functionality. This is achieved with the inheritance feature of object-oriented programming.
Before we learn what inheritance is and how to implement it in our code, let me first give you a brief introduction to the importance of having inheritance. The major advantage of inheritance is code reuse.
We will be able to use our tested code in our new applications, with desired additions, without really touching it. Even if the code has been distributed, we are able to add more functionality to our new applications without breaking the distributed code.
For example, we may have been using OpenOffice for the last several years. Haven’t you upgraded it several times during this period? When an application such as OpenOffice is upgraded, the developers do not rewrite the full code for every new version. They use the code of the existing version in terms of the classes they have defined and simply add more functionality to it without touching the source program of the existing code. This is what inheritance permits us to do.
Besides this, by using inheritance, we will be able to model the real-world hierarchies. For example, to develop a payroll system, we could define classes such as Person, Employee, Staff, Manager, Director, and so on, that perfectly fit into an inheritance hierarchy. Because such classes have a lot of commonality, putting them in an inheritance hierarchy will make our code more maintainable in the future.
The inheritance also allows us to create a set of pluggable items with the same “look and feel”. As an example, consider the various GUI (graphical user interface) controls we use in dialog boxes of our daily applications. Most of these controls, such as text boxes, list boxes, buttons, labels, and so on, have lot of commonality in terms of their functions and their look and feel. The inheritance feature of object-oriented programming facilitates creating a set of such controls.