What is inheritance in programming?
Inheritance is a mechanism or process where one class inherit the properties and functionalities from another class. Just like a child inherit characteristics from his parents. The class that inherits the properties and functionalities of another class is known as a child class/subclass. On the other hand, the class whose properties are inherited is known as the parent class/superclass.
Why do we need Inheritance?
There are several reasons why we need inheritance.
Reusability: With inheritance, we can use the fields and methods again and again, or we can reuse the whole class wherever we need. As a result, we don't have to write the same code which saves us a lot of time. For example, in the collection framework of java - Sorted Set inherit Set, Navigable set inherit Sorted set, Tree set inherits Navigable set. Here if we use the Tree set we can use all the functionalities of the Set, Sorted set and Navigable set, we don't have to write code for each of them again. That's the privilege we get from inheritance.
Maintenance: As we reuse the code, for safety the reusable code is tested more often, which means the program will have fewer errors means a better program.
Overriding: When we declare the same method in the child class which is already present in the parent class with a different implementation then this is called method overriding. When we use the child class it inherits some functionalities from the parent class, if we need to change a certain functionality because of the requirement we can do it by overriding the child class and it will execute the method of the child class, not the parent class.