Java Runtime Polymorphism with Multilevel Inheritance



In Java, multilevel inheritance allows a class to inherit attributes and methods from another class by creating a multiple layer of inheritance. Runtime polymorphism lets a child class to provide different implementations of inherited methods through method overriding. When we implement runtime polymorphism using multilevel inheritance, call to the overridden method is decided at the run time by JVM on the basis of object type.

In this article, we are going to demonstrate runtime polymorphism in Java using multilevel inheritance. But, let's discuss runtime polymorphism first.

What is Runtime Polymorphism in Java?

Runtime polymorphism is a type of polymorphism where the method call is determined at runtime based on the type of object used. It is achieved through method overriding.

In a class hierarchy, you can define a method in a subclass with the same name and type signature as a method in its superclass. Then, it is said that method in the superclass is overridden by the method in the subclass.

In method overriding, the method is called from within its subclass and it will always refer to the version of that method defined by the subclass. The method that is defined inside the superclass will be hidden.

Implementing Runtime Polymorphism in Multilevel Inheritance

Creating multiple layers of inheritance where a subclass is used as a superclass of another class is called a multilevel type of inheritance. We can override a method at any level of multilevel inheritance.

Example

See the example below to understand the concept of runtime polymorphism in multilevel inheritance:

class Grocery {
   public void weight() {
      System.out.println("Empty Grocery Cart");
   }
}
class Milk extends Grocery {
   public void weight() {
      System.out.println("1Litre Milk");
   }
}
class Curd extends Milk {
   public void weight() {
      System.out.println("500g of Curd is prepared using 1L milk");
   }
}
public class Main {
   public static void main(String args[]) {
      // Grocery reference and object 
      Grocery a = new Grocery(); 
      // Grocery reference and milk object
      Grocery b = new Milk(); 
      // Grocery reference and curd object
      Grocery c = new Curd();
      // runs the method in Grocery class
      a.weight(); 
      // runs the method in Milk class
      b.weight(); 
      // runs the method in Curd class
      c.weight();
   }
}

When you the above code, it will display the following output:

Empty Grocery Cart
1Litre Milk
500g of Curd is prepared using 1L milk
Updated on: 2025-04-17T18:52:38+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements