Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Development USbreadcumb forward arrow iconRuntime Polymorphism in Java with Examples

Runtime Polymorphism in Java with Examples

Last updated:
28th Jan, 2022
Views
Read Time
8 Mins
share image icon
In this article
Chevron in toc
View All
Runtime Polymorphism in Java with Examples

Polymorphism is a technique wherein a single action can be performed in two different ways. The term polymorphism is derived from two Greek words, ” poly” and “morphs,” which mean many and forms, respectively.  

In my experience with Java programming, I’ve gained a deep understanding of polymorphism. It’s akin to being versatile, where a single entity can exhibit different behaviors depending on the context, much like a person playing various roles in different situations. Polymorphism plays a crucial role in Object-Oriented Programming (OOP), allowing for flexible and reusable code. A specific aspect I’ve explored extensively is runtime polymorphism in Java, which involves method invocation determined by the object’s type at runtime. This insight has significantly advanced my Java programming skills, enabling me to write more efficient and adaptable code. 

An example to understand the concept of polymorphism in OOPs is as follows:

use warnings;

Ads of upGrad blog
# Creating class using package

package A;

# Constructor creation

sub new

{

    # shift will take package name 'vehicle' 

    # and assign it to variable 'class'

    my $class = shift;

    my $self = {

                  'name' => shift,

                  'roll_no' => shift

               };

    sub poly_example

    {

      print("This corresponds to class A\n");

    }

};
  
package B;

# The @ISA array contains a list 

# of that class's parent classes, if any

my @ISA = (A);

sub poly_example

{

  print("This corresponds to class B\n");

}

package main;
  
B->poly_example();

A->poly_example();

Polymorphism in Java

Polymorphism in Java can be done in two ways, method overloading and method overriding. There are two types of polymorphism in Java.

  1. Compile-time polymorphism
  2. Runtime polymorphism.

Compile-time polymorphism is a process in which a call to an overridden method is resolved at compile time. 

In this article, we’ll cover runtime polymorphism in Java in detail. 

Learn Software engineering degrees online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Purpose of Polymorphism in OOPs

The primary purpose of polymorphism is to perform a single action in multiple ways. In other words, polymorphism provides one interface with many implementations. Poly means many and morphs means forms. True to its name, polymorphism offers different forms to a single function.

Runtime Polymorphism in Java

Runtime polymorphism, also known as the Dynamic Method Dispatch, is a process that resolves a call to an overridden method at runtime. The process involves the use of the reference variable of a superclass to call for an overridden method.

The method to be called will be determined based on the object being referred to by the reference variable. 

Check out all trending Java Tutorials in 2024. 

Implementation of Runtime Polymorphism in Java 

In Java, Runtime polymorphism is one of the powerful object-oriented concepts that allows a program to perform different behaviors based on runtime type information. This is done using method overriding, allowing a subclass to offer its own implementation of a technique already declared in its parent class. 

 During the compilation time, the compiler binds a method call to the signature of the corresponding method present in the superclass. But in runtime, the type of object that the reference variable is pointing to determines which method actually gets executed. This is flexible and scalable within the code. 

 For example, suppose there is a superclass called Shape and two subclasses, Circle and Rectangle, with their own implementations of the same method called draw. In runtime, if a reference variable is created with the type Shape and initialized to refer to an object of either Circle or Rectangle types, then the relevant overriding occurrence in that particular subclass gets invoked. 

This highly dynamic method dispatch increases the modularity of code and stimulates generic code that can function efficiently with different subclasses. Therefore, runtime polymorphism is a central feature that encourages code reusability, abstraction, and inheritance in Java programming. 

Benefits of Runtime Polymorphism in Java

The primary advantage of runtime polymorphism is enabling the class to offer its specification to another inherited method. This implementation transfer from one method to another can be done without altering or changing the codes of the parent class object. Also, the call to an overridden method can be resolved dynamically during runtime. Lets discuss some benefits of polymorphism in Java 

  • Code Reusability: 

Runtime Polymorphism in Java increases the code reusability by using one method name and different classes. It ensures that standard functionalities can be implemented in a superclass and inherited by subclasses, thus reducing redundancy while increasing maintainability. 

  • Flexibility: 

Runtime Polymorphism ensures flexibility by creating a single interface that can be used to implement different types. This allows developers to modify or expand components without changing the architecture so that code can be adapted according to their needs because of the high-level flexibility in software design. 

  • Extensibility: 

Another significant benefit is extensibility since new classes or methods can easily be added without having to change the existing code. Since new subclasses can call upon and override the functions defined in a common superclass, an evolving system is modularized. As functionality changes with time, it can be easily modified to reflect changing reality. 

  • Encapsulation: 

Next, Runtime polymorphism helps to strengthen the encapsulation principle since it enables implementation details to be hidden in each class. The external code interacts with objects through a standard interface, which helps establish an apparent boundary between the internal aspects of classes and the outside parts, thereby improving maintainability and security. 

  • Polymorphic Parameters: 

Runtime Polymorphism makes it possible to process polymorphic parameters, enabling methods to accept objects of several types through a standard interface. This allows for simplified method signatures and increases the dynamic capabilities of functions, which can work with many different object types without explicitly stating each one. 

What is Method Overriding?

Runtime polymorphism in Java can be carried out only by method overriding. Method overriding occurs when objects possess the same name, arguments, and type as their parent class but have different functionality. When a child class has such a method in it, it is called an overridden method. 

What is Upcasting?

When an overridden method of child class is called through its parent type reference in Java, it is called upcasting. In this process, the object type represents the method or functionality that will be invoked. This decision is made during the runtime, and hence, the name run time polymorphism is given to the process. 

Run time polymorphism is also known as Dynamic Method Dispatch as the method functionality is decided dynamically at run time based on the object.

It is also called “Late Binding” as the process of binding the method with the object occurs late after compilation. 

Rules to be Followed When Executing Run Time Polymorphism

Below is a set of essential rules in run time polymorphism:

  • Both the child and the parent class should have the same method names.
  • Child and the parent class methods should have the same parameter.
  • It is mandatory to establish an IS-A relationship.
  • It is not possible to override the private methods of a parent class.
  • It is not possible to override static methods.

Examples of Run-Time Polymorphism in Java

Example 1

In this example, we can create two classes, car, and Audi. The  Audi class will extend the car class and override its run () method. The run method is called through the reference variable of the parent class. As the subclass method refers to the subclass object and overrides the parent class method, the subclass method will be invoked during the runtime. 

As the method to be invoked is determined by the JVM rather than the compiler, it is a classic example of runtime polymorphism.

The program for the above example can be written as follows: 

class Car{

 void run(){System.out.println("running");}

}

class Audi extends Car{

 void run(){System.out.println("running swiftly with 100km");}  

public static void main(String args[]){  

    Car b = new Audi();//upcasting  

    b.run();  

  }  

}  


    

Learn Java Tutorials

Example 2

The second example is about different shapes.

class Shape{  

void draw(){System.out.println("creating...");}  

}  

class square extends Shape{  

void draw(){System.out.println("creating square...");}  

}  

class Triangle extends Shape{  

void draw(){System.out.println("creating triangle...");}  

}  

class Pentagon extends Shape{  

void draw(){System.out.println("creating pentagon...");}  

}  

class TestPolymorphism2{  

public static void main(String args[]){  

Shape s;  

s=new Square();  

s.draw();  

s=new Triangle();  

s.draw();  

s=new Pentagon();  

s.draw();  

}  

}  


To obtain more profound knowledge about runtime polymorphism and other vital aspects in computer science, I strongly suggest you to enroll in Master of Science in Computer Science program offered by Liverpool John Moores University in association with IIT Bangalore powered by upGrad. 

The duration of the course is 20 months, the completion of which will give candidates a dual alumni status from both John Moores University and IIT Bangalore. 

Ads of upGrad blog

The curriculum includes a preparatory course that helps the candidates to have a great understanding of the Java fundamentals which will help them advance in their careers.

Candidates are mentored by industry experts to give them a relevant and practical learning experience. This is backed by over 30 case studies and projects related to the industry to help them stay in tune with the current developments in the industry.

To top all of this, the course comes with upGrad’s 360-degree placement support. upGrad has impacted the careers of more than 5,00,000 working professionals and has over 40,000 paid global learners. It provides the candidates with a fantastic opportunity of developing a vast global peer network.

Profile

Pavan Vadapalli

Blog Author
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology strategy.
Get Free Consultation

Selectcaret down icon
Select Area of interestcaret down icon
Select Work Experiencecaret down icon
By clicking 'Submit' you Agree to  
UpGrad's Terms & Conditions

Our Best Software Development Course

Frequently Asked Questions (FAQs)

1Why is method overriding also called run time polymorphism in Java?

In Java, method overriding is also called run time polymorphism because the methods are resolved during the run time rather than the time of compilation. When a program is executed, only one class's method out of so many classes will be called. This decision is made during run time.

2How can we achieve runtime polymorphism?

Runtime polymorphism is achieved by a process called function overriding that occurs when a derived class contains a definition for one of the functions of the base class members.

3How can we use inheritance to implement polymorphism?

Inheritance defines the relationship between a parent and a child class. Polymorphism uses this relationship to introduce dynamic behavior in the code or the program in general.

Explore Free Courses

Suggested Blogs

Top 19 Java 8 Interview Questions (2023)
6085
Java 8: What Is It? Let’s conduct a quick refresher and define what Java 8 is before we go into the questions. To increase the efficiency with
Read More

by Pavan Vadapalli

27 Feb 2024

Top 10 DJango Project Ideas & Topics
12775
What is the Django Project? Django is a popular Python-based, free, and open-source web framework. It follows an MTV (model–template–views) pattern i
Read More

by Pavan Vadapalli

29 Nov 2023

Most Asked AWS Interview Questions & Answers [For Freshers & Experienced]
5676
The fast-moving world laced with technology has created a convenient environment for companies to provide better services to their clients. Cloud comp
Read More

by upGrad

07 Sep 2023

22 Must-Know Agile Methodology Interview Questions & Answers in US [2024]
5397
Agile methodology interview questions can sometimes be challenging to solve. Studying and preparing well is the most vital factor to ace an interview
Read More

by Pavan Vadapalli

13 Apr 2023

12 Interesting Computer Science Project Ideas & Topics For Beginners [US 2023]
11004
Computer science is an ever-evolving field with various topics and project ideas for computer science. It can be quite overwhelming, especially for be
Read More

by Pavan Vadapalli

23 Mar 2023

Begin your Crypto Currency Journey from the Scratch
5460
Cryptocurrency is the emerging form of virtual currency, which is undoubtedly also the talk of the hour, perceiving the massive amount of attention it
Read More

by Pavan Vadapalli

23 Mar 2023

Complete SQL Tutorial for Beginners in 2024
5560
SQL (Structured Query Language) has been around for decades and is a powerful language used to manage and manipulate data. If you’ve wanted to learn S
Read More

by Pavan Vadapalli

22 Mar 2023

Complete SQL Tutorial for Beginners in 2024
5042
SQL (Structured Query Language) has been around for decades and is a powerful language used to manage and manipulate data. If you’ve wanted to learn S
Read More

by Pavan Vadapalli

22 Mar 2023

Top 10 Cyber Security Books to Read to Improve Your Skills
5534
The field of cyber security is evolving at a rapid pace, giving birth to exceptional opportunities across the field. While this has its perks, on the
Read More

by Keerthi Shivakumar

21 Mar 2023

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon