Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Runtime Polymorphism in Java with Examples

Updated on 21 October, 2024

42.97K+ views
6 min read

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;

# 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. So, Let’s explore compile-time polymorphism and run time 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. 

Also Read: Polymorphism In OOPS

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. Let’s 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();  

  }  

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. 

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.

Frequently Asked Questions (FAQs)

1. Why 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.

2. How 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.

3. How 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.

4. What is the difference between run time and compile time polymorphism in Java?

In Java, compile-time polymorphism (method overloading) occurs at compile time, allowing different methods with the same name but different parameters. Runtime polymorphism (method overriding) happens at runtime, allowing a subclass to provide a specific implementation of a method already defined in its superclass.

5. What is compile time polymorphism example?

Compile-time polymorphism in Java, like method overloading, allows multiple methods with the same name but different parameters. For example, add(int, int) and add(int, int, int).

RELATED PROGRAMS