If you have a method that you want to use in different classes. Inheritance in java gives the opportunity to make the method once. As a consequence it is not necessary to rewrite or change the method in every class. You make the particular method once and it will work in every class that you will use it in.
Example:
You got a lot of pets and you want to safe their characteristics. One way to do this is categorise their characteristics. So for example. If you want to know the color of your pets. You could do it like this but it will cost more time when you got a lot of different pets.
As mentioned in the intro it is possible to do it more easily, by categorising the pets.
This is inheritance
(and for this example the easiest way to safe the data)
Make a fourth class, also called the SUPER class:
Now you could erase line 5,6,7 in the classes dog and cat:
and add for both classes the extends keyword. In this you let the classes inherit (that is why it is called inheritance) the characteristics of the class it extends. Resulting in this:
The method: start, in the main class (pets) will work exactly the same. In this, it will safe time. In the case of a bigger class, inheritance will optimise your code in a way of shorter code and it will be better readable because everything is in its own class.
Advantage
- you could overwrite a particular class. More information here