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
6 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 real-time, polymorphism can be explained as the different roles played by a single person. For instance, a man can be a son, husband, father, etc. In other words, a person has many features and implements each one of them according to the situation. 

Polymorphism is one of the key aspects of Object-Oriented Programming (OOP). Languages incapable of supporting Object-Oriented programming do not come under Object-oriented languages.

Languages that have class but cannot support polymorphism are object-based languages and are an integral part of Object-Oriented Programming languages.

Ads of upGrad blog

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

use warnings;

# 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. 

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.

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();  

  }  

}  

 

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, enroll in the 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

Select Coursecaret down icon
Selectcaret 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

Most Asked AWS Interview Questions & Answers [For Freshers & Experienced]
5518
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

Top 19 Java 8 Interview Questions (2023)
5544
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

06 Sep 2023

22 Must-Know Agile Methodology Interview Questions & Answers in US [2023]
5293
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]
7381
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
5346
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 2023
5395
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
5360
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

Top 10 Highest Paying Programming Languages In US [2023]
7708
Language is used as a form of communication between two people. One person expresses their thoughts and opinions, whereas the other listens and compre
Read More

by Pavan Vadapalli

19 Mar 2023

Top 10 Cyber Security Books to Read to Widen Your Knowledge
6506
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 Pavan Vadapalli

18 Mar 2023

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