Inheritance

5. Inheritance

Inherit means to derive something from parents/ancestors. That something can be properties/traits. Similarly, In java we can have a parent class from whom the child class can derive its properties.

Now, It is possible that a parent might pass some properties/traits to its children but there are certain properties which are only possessed by the child only. Similarly, In java you can have all the common properties/traits in the parent class and the special qualitities/properties only available in the child classes.

A real world inheritance below:

Inheritance

Genetic Inheritance

Can you see similarity . The kids have derived their sweetness and cuteness from the Lady(mother) in between.

Okay, If you don’t find them sweet then at least would you not agree that all three have similar hair style.

Let us take our Car example once again:

Car Parent Class

Car Parent Class

Mercedes Child Class

Mercedes Child Class

As you can see how all the properties and methods that all brands of car will have in general, are put in the Car super class and behavior like openAirBag which is available in only premium cars like Mercedes are available separately in those classes.The common properties and methods are inherited in the child class Why do we do so???? Well, there are lot of advantages and its a good design. You are reusing the code. isn’t it!

This was one way to achieve inheritance, by extending another class.

Another was to achieve Inheritance is by implementing an Interface.