What is Inheritance in Java

What is Inheritance in Java?

Inheritance In java is a feature that allows a class to extend the functionality of another class by directly deriving from it. The derived class has access to all the public and protected variables and methods of the base class. Inheritance allows adding functionalities over and above those defined in the base class. We will go into the various aspects of inheritance in the subsequent tutorials, but for now here’s an example – We built a Mathematician class in the previous tutorial

We now create an AdvancedMathematician who can not only add but also subtract! One way to do that is to create two methods in a new class (without inheritance)

This works, however, it just duplicates code. Imagine what would happen if Mathematician had 50 methods and the AdvancedMathematician adds just one more method. Without inheritance, we would end up with 50 methods in Mathematician class and 51 methods in the AdvancedMathematician class. With the use of inheritance, however, we can do this:

That was much better since now our AdvancedMathematician can add as well as subtract since it inherits the performAddition method. A client that instantiates the AdvancedMathematician class can call the performAddition method on AdvancedMathematician although that method has been defined in the base class. To understand what methods can be inherited by the base class, look at this tutorial on access modifiers in Java.

limitation of inheritance in java

One important limitation that you would need to remember is that in Java a class cannot extend two classes. In other words, a class can be derived from only one class.
This is NOT allowed:

However, a class can implement more than one interface

A class can both extend a class and implement an interface

What is Inheritance in Java

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to top