Inheritance in Java

In java, Inheritance is a concept by which an object of child class can acquire all the methods and properties of the parent class. We use a keyword extends in class signature to acquire properties of another class like shown below.

e.g.    public class A extends B{ }

Where A is the child class or subclass and B is the parent class ,also called the super class.

Importance of Inheritance:

  1. Used for method overriding or say to achieve run time polymorphism.
  2. Improves the code -reusability

Inheritance is used to make a relationship between 2 classes. There is a IS-A relationship developed between those classes.

Let’s understand with an example.

Suppose, we have a Parent class named as Bank, and there are subclass named as HDFCBank. Bank class has a home loan interest which should apply in other bank also. So, HDFCBank will acquire the properties from Bank class as shown below.

So,there is a IS-A relationship between these 2 classes, as it says HDFCBank IS-A Bank.

Output : Home loan interest is 12.5

Child class can add its own method and properties as well. Have a look at the example below.HDFCBank is adding its own vehicleLoanInterest as well.

Output : Home loan interest is 12.5 Vehicle loan interest is 10.0

Multiple Inheritance is not possible in java through classes.

Multiple subclasses can extend one parent class, but one subclass can not extend multiple parent. Let’s understand with the diagram below.


Why multiple Inheritance is not possible?

As we have seen above , suppose there are 2 parent classes BankA and BankB and child class HDFCBank. There is a common field named HomeLoanInterst in both the parent classes. Now, if child class wants to access that field ,it will be confused which one it should access i.e. from BankA or BankB.

Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.



this keyword
Aggregation in java
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *