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

Understanding Runtime Polymorphism with Example

Updated on 06 December, 2024

43.25K+ views
15 min read

Did you know that runtime polymorphism is one of Java's hidden strengths? It’s like Java having the flexibility to decide which method to call at the right moment, depending on the actual object type, not just the reference type. 

In simple terms, runtime polymorphism helps manage different object types as if they are part of the same family, improving code flexibility and scalability. As Java is one of the world’s fourth most in-demand languages, mastering runtime polymorphism can significantly enhance your Java programming skills.

Think of it as Java having the smarts to adjust on the go, based on the context. It’s what gives your code versatility and future-proofing abilities. 

In this article, you’ll dive deeper into how runtime polymorphism works, example of polymorphism in Java and how it can improve your skills.

Let’s explore!

How Does Runtime Polymorphism Implemented?

Runtime polymorphism is a powerful concept that provides flexibility in Java. It allows you to invoke methods dynamically at runtime based on the actual object type, not just the reference type and is also one of the most used polymorphisms in Java.

Let’s break it down step by step.

  • The core of runtime polymorphism is Dynamic Method Dispatch. It ensures that the method call is resolved at runtime based on the actual object type rather than the reference type. 
  • It enables Java to decide which method to invoke when you call an overridden method on a parent class reference pointing to a child class object.
  • When the program runs, the JVM dynamically chooses the method to execute, making the system more flexible and adaptable. 
  • This is what makes Java a powerful, object-oriented language that utilizes runtime polymorphism.

Steps to Implement Runtime Polymorphism

Now, let’s look at the key steps you need to follow to implement runtime polymorphism.

  • Step 1: Create a Parent Class 

Start by creating a parent class using a method (like display() or makeSound()).

  • Step 2: Create a Subclass 

Next, create a subclass that overrides the parent class method. This allows the subclass to provide its own version of the method.

  • Step 3: Use Upcasting 

Assign the subclass object to a reference of the parent class type. This is known as upcasting, where a subclass object is treated as an object of the parent class.

  • Step 4: Call the Overridden Method 

Finally, call the overridden method using the parent class reference. At runtime, Java will invoke the appropriate method based on the actual object type, not just the reference type.

Moving ahead, let’s see these steps in action with an example. 

In this scenario, we have a parent class Animal and a subclass Dog. The Dog class overrides the makeSound() method from the Animal class.

Example Code:

// Parent Class
class Animal {
    public void makeSound() {
        System.out.println("Animal makes sound");
    }
}

// Child Class
class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Dog barks");
    }
}

// Main Class
public class TestPolymorphism {
    public static void main(String[] args) {
        Animal myAnimal = new Animal();  // Parent class reference
        Animal myDog = new Dog();         // Child class reference, upcasted to Parent class

        myAnimal.makeSound();  // Outputs: Animal makes sound
        myDog.makeSound();     // Outputs: Dog barks
    }
}

Output of the Code:

Animal makes sound
Dog barks

Explanation of the Code:

  • Parent Class (Animal): The Animal class defines a method makeSound(), which outputs "Animal makes sound".
  • Child Class (Dog): The Dog class inherits from Animal and overrides the makeSound() method. The overridden method prints "Dog barks" instead of the generic animal sound.
  • Upcasting: In the TestPolymorphism class, we use upcasting:
    • myAnimal is a reference of type Animal pointing to an instance of Animal.
    • myDog is a reference of type Animal but points to a Dog object. This allows us to treat the subclass object as if it’s of the parent class type.
  • Method Calls:
    • When myAnimal.makeSound() is called, the method from the Animal class is executed.
    • When myDog.makeSound() is called, despite the reference being of type Animal, the method in the Dog class is executed due to runtime polymorphism.

Here’s a quick summary of the steps to implement runtime polymorphism in Java.

Step

Action

Description

1 Create Parent Class Define the parent class with a method to be overridden.
2 Create Subclass Create a subclass that overrides the parent's method.
3 Use Upcasting Assign the subclass object to a reference of the parent class type.
4 Call the Overridden Method Use the parent class reference to call the method and let JVM resolve the correct method at runtime.

Also Read: Types of Polymorphism in Java [Static & Dynamic Polymorphism with Examples]

Examples of Runtime Polymorphism in Java

Runtime polymorphism lets your Java pick the right method to run based on the actual object it’s working with—no matter what type of reference you use. This makes your code more flexible and easier to tweak as it adapts to different objects seamlessly.

To clarify, a method for calculating speed might work differently for a car than for a bicycle, even though both use the same method name. This flexibility, through method overriding and interfaces, enables scalable and adaptable code.

Here are two examples of how runtime polymorphism can be implemented in Java.

Example 1: Method Overriding with Parent and Child Classes

In this example of polymorphism in Java, method overriding occurs when a child class provides a specific implementation for a method defined in its parent class. 

The real power of runtime polymorphism comes when you use a parent class reference to invoke a method on a child class object. 

This allows you to use the same method name but have different implementations depending on the object’s actual class type.

Example Code:

class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Dog barks");
    }
}

public class TestPolymorphism {
    public static void main(String[] args) {
        Animal myAnimal = new Animal(); // Parent class reference
        Animal myDog = new Dog();       // Child class object

        myAnimal.sound(); // Outputs: Animal makes a sound
        myDog.sound();    // Outputs: Dog barks
    }
}

Output:

Animal makes a sound
Dog barks

Explanation:

Here, Animal is the parent class with a sound() method. The Dog class overrides this method and provides its own implementation. 

Even though myDog is declared as an Animal reference, at runtime, Java dynamically binds the method call to the Dog class's sound() method. 

This is the essence of runtime polymorphism: The method called depends on the actual object (Dog), not the reference type (Animal).

Also Read: Difference Between Overloading and Overriding | Overloading vs Overriding

By now, you've seen how runtime polymorphism operates within class hierarchies. Next, let's dive into how it can be applied to interfaces and abstract classes for even greater flexibility in your code.

Example 2: Using Interfaces and Abstract Classes for Runtime Polymorphism

In this example of polymorphism in Java, Runtime polymorphism is not limited to class inheritance. 

You can also achieve polymorphism through interfaces and abstract classes, allowing different classes to implement their own versions of a method defined by an interface or abstract class. 

This further extends Java's flexibility, as different types of objects, all implementing the same method, can be handled uniformly.

Example Code:

interface Animal {
    void sound();
}

class Cat implements Animal {
    @Override
    public void sound() {
        System.out.println("Cat meows");
    }
}

class Bird implements Animal {
    @Override
    public void sound() {
        System.out.println("Bird chirps");
    }
}

public class TestPolymorphism {
    public static void main(String[] args) {
        Animal myCat = new Cat();  // Using Interface reference
        Animal myBird = new Bird(); // Using Interface reference

        myCat.sound();  // Outputs: Cat meows
        myBird.sound(); // Outputs: Bird chirps
    }
}

Output:

Cat meows
Bird chirps

Explanation:

In this example of polymorphism in Java, the Animal interface defines a method sound(), which the Cat and Bird classes implement differently. 

The real benefit of polymorphism is evident when we use an Animal reference to hold different objects (E.g., a Cat or a Bird). 

At runtime, Java determines which class's sound() method to invoke based on the actual object type, allowing you to use the same method name for different behaviors.

Also Read: Virtual Function in Java

What is Method Overriding?

Method overriding in Java is a fun yet powerful feature that lets a subclass redefine a method from its parent class to suit its needs. It is similar to an employee tailoring a standard procedure while still following the core principles.

In the world of Java, using this you can modify the behavior of inherited methods, enabling dynamic decision-making at runtime.

Now that you understand method overriding, let's discuss the key conditions you need to follow.

  • Same Method Name: The method name in the subclass must match the name in the parent class. 
    • For example, if your parent class has a drive() method, the subclass must also define a drive() method.
  • Same Parameter List: The parameter list in the subclass method must exactly match the one in the parent class. 

So, if the parent’s drive() method takes two integers, your subclass method must do the same.

  • Same Return Type: The return type must also match. If the parent method returns an int, your subclass method should return the same type or a subclass of it.
  • Types of Inheritance: The method being overridden must be part of the parent class i.e., you can't override a method from a class you don't inherit from.
  • Use of @Override Annotation (Optional but Recommended): Although it's not mandatory, it’s best practice to use @Override to ensure you're truly overriding a method and not accidentally overloading it.

With the conditions set, let's discuss how method overriding powers runtime polymorphism in Java code.

Relationship Between Method Overriding and Runtime Polymorphism

So, why does method overriding matter? It’s the magic behind runtime polymorphism in Java! Polymorphism lets the method that gets called depend on the actual object type, not just the reference type. 

Imagine you have a Car class and a Truck class, both overriding a method like StartEngine (). 

Even if you're using a reference of type Vehicle, Java will call the right method at runtime—startEngine() for a Car or a Truck.

Let’s break this down further to see how it works in different scenarios.

  • Upcasting in Overriding: 

Upcasting allows you to assign a subclass object to a parent class reference. Despite the reference being of the parent class type, Java will still call the overridden method in the subclass. 

Think of it like following a proven business strategy, where each team (class) adds their own unique approach to make it their own.

  • Dynamic Method Dispatch: 

Here’s where the JVM does its magic. It decides at runtime which version of the method to call based on the actual object. 

It’s like a project manager selecting team members based on their strengths and availability, rather than strictly sticking to the original plan.

It’s time to see these concepts in action, so let’s walk through an example of method overriding and runtime polymorphism.

Example:

A Practical Demonstration of Method Overriding Enabling Runtime Polymorphism.

// Parent class
class Vehicle {
    public void startEngine() {
        System.out.println("Vehicle engine starts");
    }
}

// Child class
class Car extends Vehicle {
    @Override
    public void startEngine() {
        System.out.println("Car engine starts with a roar!");
    }
}

// Main class
public class TestPolymorphism {
    public static void main(String[] args) {
        Vehicle myVehicle = new Vehicle();  // Parent class reference
        Vehicle myCar = new Car();           // Child class reference, upcasted to Parent class

        myVehicle.startEngine();  // Outputs: Vehicle engine starts
        myCar.startEngine();      // Outputs: Car engine starts with a roar!
    }
}

Output:

Vehicle engine starts
Car engine starts with a roar!

Explanation of the Code:

  • Parent Class - Vehicle: 

The Vehicle class has a method startEngine(), which prints "Vehicle engine starts". This is a simple method in the parent class.

  • Child Class - Car: 
    • The Car class inherits from Vehicle and overrides the startEngine() method. 
    • The @Override annotation ensures that Java knows this method is being overridden from the parent class. 
    • The child class version of startEngine() prints "Car engine starts with a roar!", giving a more specific implementation.
  • Upcasting in Main:

 In the TestPolymorphism class, two objects are created:

  • myVehicle is a reference method of Vehicle pointing to an instance of the Vehicle class.
  • myCar is a reference of type Vehicle pointing to an instance of the Car class.
  • This is called upcasting—even though the reference is of type Vehicle, it refers to a Car object.
  • Method Calls:
    • When myVehicle.startEngine() is called, the method in the Vehicle class is executed, outputting "Vehicle engine starts".
    • When myCar.startEngine() is called, despite the reference being of type Vehicle, the JVM dynamically determines that the actual object is of type Car. 
    • So, it calls the Car class's overridden startEngine() method, printing "Car engine starts with a roar!".

After seeing the example, let’s go over the important rules you need to keep in mind to implement runtime polymorphism correctly.

  • Same Method Signature: Ensure the method name, parameters, and return type match exactly between the parent and subclass.
  • Inheritance Required: The parent class method must be available to the subclass for overriding.
  • Instance Methods Only: Static methods, private methods, and constructors cannot be overridden.
  • Dynamic Dispatch at Runtime: The JVM uses dynamic dispatch to determine which method to call based on the actual object, ensuring flexibility and scalability.

Also Read: Memory Allocation in Java: Everything You Need To Know 

What are the Advantages and Disadvantages of Runtime Polymorphism in Java?

Runtime polymorphism is a key feature driving innovation in modern software development. 

While runtime polymorphism offers great benefits, understanding its challenges is also essential. This knowledge helps you maximize its potential while effectively managing any complexities it may bring.

Ready to make the most of it in your projects? Let’s dive into its advantages and disadvantages.

Advantages of Runtime Polymorphism

Think of runtime polymorphism as a versatile tool in your coding toolkit. It lets your program adapt and perform different tasks without rewriting the whole system, giving you cleaner, more efficient code.

Here’s how their strengths stack up.

  • Code Reusability: For example, in a payment system, overriding processPayment() for different payment types avoids repetitive code, increasing efficiency.
  • Flexibility: Polymorphism allows classes like CreditCardPayment and PaypalPayment to use the same method but behave differently, offering adaptable solutions.
  • Scalability: Like adding new delivery methods in a logistics system, polymorphism allows new features without altering existing code.
  • Easier Maintenance: Changes in parent classes automatically apply to subclasses, reducing the maintenance effort, as seen in updating payment gateways.

Disadvantages of Runtime Polymorphism

While runtime polymorphism can enhance your code, it’s essential to be aware of its drawbacks. 

Improper usage or overuse can introduce performance and complexity issues that may hinder your application's efficiency and maintainability.

Here’s a closer look at all such limitations.

  • Performance Overhead: Dynamic method resolution adds extra steps, slowing down applications, similar to checking ingredient supplies in a restaurant.
  • Increased Complexity: Too many overridden methods can complicate debugging, like trying to trace multiple payment methods in a banking system.
  • Risk of Misuse: Overusing polymorphism can lead to unnecessary complexity, making code harder to understand, much like overcomplicating a game with excessive object types.
  • Memory Consumption: Frequent dynamic method calls use more memory, impacting large applications with many classes, such as apps with numerous user interactions.

Curious to know more about example of Polymorphism in Java? Start your journey with upGrad’s Core Java course today  and gain essential skills!

What are the Real-World Use Cases of Runtime Polymorphism?

Runtime polymorphism in Java is like a code ninja—it effortlessly adjusts its behavior in real-time!

By using method overriding and dynamic resolution at runtime, your code stays flexible and scalable, allowing it to adapt without major changes. This makes it perfect for building versatile applications that grow as easily as they evolve.

Here are some real-world use cases where runtime polymorphism plays a vital role.

Graphical User Interface (GUI) Applications

Runtime polymorphism is magic in GUI frameworks like Swing or JavaFX. It lets components like buttons and text fields perform different actions depending on what is clicked. 

For instance, clicking a "Submit" button triggers one action, while a "Reset" button triggers another, making your app interactive and responsive to user actions.

Frameworks like Spring

The Spring framework uses runtime polymorphism for Dependency Injection (DI), letting different beans (objects) be injected based on runtime conditions. 

This keeps your application flexible and scalable, with bean behavior changing depending on the runtime implementation—just like swapping parts to customize performance without rewriting the whole system!

Method Overriding in Collections

Polymorphism in collections is like a multi-tasking pro—different objects, same methods! 

In Java, collections like List, Set, and Queue store various objects. Each can override methods like add() and remove() to handle specific types. 

It’s runtime polymorphism in action. Each collection handles tasks independently, keeping your code adaptable and efficient.

Design Patterns (Factory and Strategy Patterns)

In design patterns like Factory and Strategy, runtime polymorphism acts like a real-time decision-maker for you, picking the right class or method based on runtime inputs.

 It’s especially useful in dynamic systems, like a payment gateway, where the system can switch between different providers depending on the situation—making everything run smoothly without a glitch!

Web Services and APIs

Polymorphism is useful when a web service needs to return different responses based on the request type or parameters. 

For example, One API endpoint can handle multiple data requests—whether XML or JSON—and return different objects based on the request type. It’s like a multi-tool that adapts to your needs!

Unit Testing and Mocking

During unit testing, runtime polymorphism allows you to mock specific behaviors of a class. 

Test frameworks like JUnit use this feature to replace real object behaviors with mock objects, helping you simulate and test specific conditions efficiently. 

This makes testing more flexible, letting you focus on testing only what’s necessary while keeping your tests clean and maintainable.

Database Operations

In database applications, runtime polymorphism is like a smart switch for you—automatically choosing the right data access object (DAO) depending on the database management system in use. 

This allows the system to work with multiple databases without needing to change the code structure, keeping things flexible and efficient.

Can Java drive your data career forward? Definitely! upGrad’s Master’s Degree in Artificial Intelligence and Data Science course prepares you for the challenges of the future. Start your journey now!

How Can upGrad Help You Build a Career in Programming?

With over 1 million+ learners globally enhancing their skills, upGrad has established itself as a leader in programming education. 

Our programming courses combine industry-relevant curricula, hands-on projects, and mentorship to help you stay ahead in a competitive tech environment. 

Here’s how upGrad supports your programming journey.

  • Full Stack Development CourseMaster the art of building dynamic applications using Java for the back end and React for the front end.
  • Job-Ready Full Stack Developer: Become proficient in both front-end and back-end development with a detailed curriculum that includes key technologies like Java, React, and JavaScript.
  • Java Object-oriented Programming:  Establish a strong foundation in Java with a focus on object-oriented principles, which are crucial for back-end development.
  • JavaScript Basics from Scratch: Strengthen your programming skills with JavaScript and explore essential web development concepts to create interactive applications.

Not sure where to begin? upGrad offers personalized career counseling to help you choose the right course. From exploring an example of polymorphism in Java to mastering full-stack development or diving into data science, there’s a course for you.

Start your journey today and open doors to exciting tech career opportunities with upGrad!

Master Java with step-by-step tutorials, practical examples, and expert tips to enhance your programming skills.

References:
https://economictimes.indiatimes.com/magazines/panache/these-are-the-highest-paying-programming-languages-you-should-learn-ranked-by-salary/articleshow/45258811.cms?from=mdr

Frequently Asked Questions (FAQs)

1. How is runtime polymorphism different from compile-time polymorphism?

Runtime polymorphism happens through method overriding and gets resolved during program execution. While, compile-time polymorphism relies on method overloading and gets resolved while the code is compiled.

2. Why does method overriding enable runtime polymorphism?

Method overriding allows subclasses to redefine parent class methods. This ensures the right method is executed at runtime, depending on the actual object type.

3. What does dynamic method dispatch mean in Java?

Dynamic method dispatch refers to the JVM deciding which overridden method to execute during runtime based on the object's runtime type.

4. Can runtime polymorphism involve static methods?

No, static methods are resolved at compile time and do not support runtime polymorphism.

5. How does inheritance help with runtime polymorphism?

Inheritance allows subclasses to inherit and override parent class methods, forming the foundation for runtime polymorphism.

6. Where can you see runtime polymorphism in action?

You’ll find it in systems like payment processing, GUI event handling, and behavior-driven applications like video games.

7. Do abstract classes and interfaces support runtime polymorphism?

Absolutely! Abstract classes and interfaces let subclasses implement or override their methods, enabling polymorphic behavior at runtime.

8. What role does the JVM play in runtime polymorphism?

The JVM dynamically determines which method to execute by checking the object's actual type during runtime.

9. What challenges might you face with runtime polymorphism?

Debugging dynamic behavior can be tricky, and runtime resolution might slightly impact performance.

10. How do interfaces improve runtime polymorphism?

Interfaces define methods that various classes can implement, enabling dynamic method invocation across multiple implementations.

11. Can runtime polymorphism make your code easier to manage?

Yes, it simplifies your code by decoupling method calls from specific implementations, making updates and scaling much smoother.

RELATED PROGRAMS