Inheritance is a way or mechanism which enable a class or object to acquire or inherit some or all properties and functionality of another class.
Class which acquire properties and functionality from another class is known as ‘Derived’, ‘Child’ or ‘Sub’ class. And class from which it acquire these properties and functionality is known as ‘Parent’, ‘Super’ or ‘Base’ class.
Inheritance is one of the most powerful and important feature of Object-Oriented Programming. As it enable us to derive child classes or objects and help us saving time and reuse of existing code.
Let’s take a real world example for better understanding. Let’s assume we are creating a learning management system for a university or school. This learning management system will enable us to manage and record data related to students, teachers and all other staff.
Now students, teachers and staff members have some common properties. Because, they all are humans. They all have name, address, age, gender and other common attributes. What if we want to create classes for all of these in our learning management system? Without inheritance your Student, Teacher and Staff classes might look like this.
Obviously this don’t look good. As we will have to write almost same properties and methods in all three classes. And it will result in repeated or spaghetti code. That’s why inheritance become very important; As it provide us a mechanism to save time by creating one class with all common properties and functionality and reuse it as many time as we want to. This is how our classes will look like with inheritance.
Now you see, how inheritance help us to write once and use as many time as we would like to? Because, we will create a base class ‘Person’ with all common properties and methods and derive all three classes with these properties and methods from it. Derive classes will automatically inherit all functionality of Base class.
And also if we will have to change something or extend in our Person class. Let’s say we would like to breakdown address into address 1, address 2, city, state and country. We will only have to change it in our super or base class, i.e. Person, and our all other derived classes will automatically inherit these changes.
I think this should be enough for Inheritance. But, if you still have any confusion on this, please ask your questions as comments below.
Let’s move on to our next chapter. Please click on ‘Next’ to continue.