Inheritance is one of the main concepts in Object Oriented Programming (OOP). Using inheritance, we can model a problem properly and we can reduce the number of lines we have to write. Let's see inheritance using a popular example.
Consider you have to model animal kingdom (Simplified animal kingdom, of course. Biologists, pardon me) using OOP. There are a lots of species of animals, some have unique features, while some share same features.
There a are main families of animals. Let's say, Mammals
, Reptiles
.
Then we have children of those families. For an example,
Cat
, Dog
, and Lion
are mammals.Cobra
and Python
are reptiles.Every animal shares some basic features like eat
, drink
, move
. Hence we can say that we can have a parent called Animal
from which they can inherit those basic features.
Then those families also shares some features. For an example reptiles use crawling to move. Every mammal is fed milk
at early stages of life.
Then there are some unique features for each and every animal.
Consider if we are to create these animal species separately. We have to write same code again and again in every animal species. Instead of that, we use inheritance. We can model the Animal Kingdom as follows:
Animal
, which have basic features of all the animals.Mammal
and Reptile
(of course the other animal families also) objects with their common features while inheriting the basic features from parent object, Animal
.Cat
and Dog
inherits from Mammal
object, Cobra
and Python
inherits from Reptile
object, and so on.In this form we can reduce the code we write, as we do not need to define basic features of Animals in each animal species, as we can define them in the Animal
object and then inherit them. Same thing goes with the animal families.