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.
- Compile-time polymorphism
- 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();    }  }
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.Â
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
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.
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.
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.
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.
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).