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

public class Mathematician {
  public static double performAddition(double a, double b) {
      return a+b;
  }
}

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)

public class AdvancedMathematician {
  public static double performAddition(double a, double b) {
      return a+b;
  }
  public static double performSubtraction(double a, double b) {
      return a-b;
  }
}

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:

public class AdvancedMathematician extends Mathematician{
   public static double performSubtraction(double a, double b) {
      return a-b;
  }
}

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:

public class ClassA extends ClassB,ClassC

However, a class can implement more than one interface

public class ClassB implement InterfaceA, InterfaceB

A class can both extend a class and implement an interface

public class ClassA extends ClassB implements InterfaceA, InterfaceB

Leave a Reply

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