Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconPolymorphism In OOPS: What is Polymorphism [Detailed Explanation]

Polymorphism In OOPS: What is Polymorphism [Detailed Explanation]

Last updated:
21st Sep, 2022
Views
Read Time
14 Mins
share image icon
In this article
Chevron in toc
View All
Polymorphism In OOPS: What is Polymorphism [Detailed Explanation]

Polymorphism in OOPs is inseparable and an essential concept of every object-oriented programming language. An object or reference basically can take multiple forms in different instances. As the word suggests, ‘poly’ means ‘many’ and ‘morph’ points at ‘forms’; thus, polymorphism as a whole would mean ‘a property of having many forms.’

The object-oriented programming language processes classes and objects by a single interface. It implements the concepts of function overloading, overriding, and virtual functions. Also, it is typically used for instrumenting inheritance in programming. 

Polymorphism is one of the significant OOPS concepts. Using Polymorphism, you can have various or multiple forms of objects, variables, or methods. There can be varied implementations of the same method as per the class’ need using Polymorphism.

The concept of polymorphism offers great scalability and boosts the code’s readability. You can define polymorphism to have your unique implementation for the same method within the Parent class. Generally, it can be obtained using inheritance which implies that the class must belong to the same hierarchy tree. Knowing more about Polymorphism implementation in the programming world and how you can access it using the class object is necessary.

Ads of upGrad blog

It denotes an object’s/reference’ ability to adopt several forms in various instances. It uses the concept of function overriding, function overloading, and virtual functions.

Polymorphism is a property using which any message could be delivered to objects of multiple classes. Each object owns the tendency to respond appropriately based on the class properties.

It implies that polymorphism is the method in an OOP language that performs different things based on the class of the object that calls it. For instance example, $rectangle->area() will return the area of a rectangle, but $square->area() will return the area of a square. But $object->area() will have to calculate the area based on which class $object was called.

Why is polymorphism used?

The concept of polymorphism helps you to perform a single action in various ways. It helps you to define one interface and benefit from multiple implementations. The term to explain polymorphism is such that the word “poly” indicates many and “morphs” indicates forms. Hence, it implies many forms.

Benefits of Polymorphism in OOPS:

Polymorphism aids the developer in reusing the program codes. It suggests that the old codes and classes written once, confirmed, and executed can be reused when required. This saves a programmer’s time. Hence, these codes and associated classes may be relevant to other methods.

Only a single variable can be used for storing multiple data types like Float, Int, Long, Double, etc. It simplifies the process of searching and executing the types of variables the users utilize.

You can define polymorphism to simplify code debugging. It assists in maintaining and reducing the coupling among different functionalities.

It benefits programmers with the flexibility to write programs that uses just one method for several executions as required. This method can work inversely for various inputs based on the interface type.

One of the biggest benefits to explain polymorphism is that it allows the programming code to expand itself to use the previous program. Thus, it saves the developers’ effort and time.

The core theory of OOPs languages is also implemented for programming various forms of large execution of codes.

The Polymorphism feature lets programming become more resourceful and faster for code development.

It decreases coupling and maximizes reusability to code a readable program.

Also, Check out our free courses

Read: Polymorphism vs Inheritance

An Example of Polymorphism in OOPs

Polymorphism is the method in an object-oriented programming language that performs different things as per the object’s class, which calls it. With Polymorphism, a message is sent to multiple class objects, and every object responds appropriately according to the properties of the class. 

Following is the code that explains polymorphism clearly:

use warnings;
# Creating package class
package A;
# Creating Constructor
sub new
{
# shift will take package name
# and assign it to variable ‘class’
my $class = shift;
my $self = {
‘name’ => shift,
‘roll_no’ => shift
};
sub method
{
print(“This belongs to class A “);
}
};
package B;
# The @ISA array contains a list
# of that class’s parent classes, if any
my @ISA = (A);

submethod
{
print(“This belongs to class B”);
}
package main;
B->method();
A->method();

Output:

This belongs to class B

This belongs to class A

Learn to build applications like Swiggy, Quora, IMDB and more

Get Software Development Course from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Explanation

For the first output, the method() defined in class B overrides the definition inherited from class A and vice-versa for the second output. This property is useful in extending any pre-existing package’s functionality without rewriting the entire class’s entire definition. Thus, making the job easy for the programmer and the reason for being used widely.

Check out upGrad’s Full Stack Development Bootcamp

Important concepts about Polymorphism in OOPS:

What are the principles of Polymorphism in OOPS?

The dictionary definition of OOP polymorphism relates to the biology principle in which species or organisms can have several different stages or forms. This principle can be applied to object-oriented programming and languages such as Java.

 What is overloading and overriding in Polymorphism?

In OOP polymorphism, overloading happens when two or more methods in one class share the same method name but with unique parameters. It happens when two methods share the same method name and parameters. These are the two common methods for overloading and overriding Polymorphism in the parent and child classes.

What are compile-time and runtime in Polymorphism?

Compile time is when the programming code (like C, C#, Java, Python) is transformed into the machine code i.e. binary code. Runtime is when a program is executing and usually happens after compile time.

Which type of function shows Polymorphism?

Compile time polymorphism is obtained by operator overloading or function overloading. Function overloading is when there are multiple functions with similar names. If varied parameters are used, then these functions are said to be overloaded.

What is a method in OOP?

The method in polymorphism explains that it is a programmed process that is defined as part of a class and incorporated into any object of the particular class. A class and an object can have multiple methods.

Explore our Popular Software Engineering Courses

Master of Science in Computer Science from LJMU & IIITBCaltech CTME Cybersecurity Certificate Program
Full Stack Development BootcampPG Program in Blockchain
Executive Post Graduate Programme in Software Development – Specialisation in DevOpsExecutive PG Program in Full Stack Development
View All our Courses Below
Software Engineering Courses

Types of Polymorphism in Oops

In Object-Oriented Programming (OOPS) language, there are two types of polymorphism as below:

  1. Static Binding (or Compile time) Polymorphism, e.g., Method Overloading
  2. Dynamic Binding (or Runtime) Polymorphism, e.g., Method overriding

Source

In-Demand Software Development Skills

JavaScript CoursesCore Java CoursesData Structures Courses
Node.js CoursesSQL CoursesFull stack development Courses
NFT CoursesDevOps CoursesBig Data Courses
React.js CoursesCyber Security CoursesCloud Computing Courses
Database Design CoursesPython CoursesCryptocurrency Courses
  1. Compile Time or Static Polymorphism

With Method Overloading, static polymorphism is achieved in Object-Oriented Programming languages that allow the programmer to implement various methods. The names they use can be the same, but their parameters are different.

In OOPS, you can attain compile-time polymorphism using method overloading. Java recognized which method to call after checking the corresponding method signature. In the method overloading polymorphism concept, there can be the same method name but a different number of arguments and the return type to execute this. In a nutshell, when the object is limited to its functionality, it is called compile time polymorphism.

In OOPS, you can attain compile-time polymorphism using method overloading. Java recognized which method to call after checking the corresponding method signature. In the method overloading polymorphism concept, there can be the same method name but a different number of arguments and the return type to execute this. In a nutshell, when the object is limited to its functionality, it is called compile time polymorphism.

Certain conditions are conducive to static polymorphism as below:

  •       Types of All Parameters should be different.
  •       The sequence of the Parameters can be different.
  •       The number of parameters of one method should differ from the other method.

In the static binding polymorphism, the matching type and number of arguments invoke the overloaded functions. 

  • As all of this information is available during the compile time, the compiler selects the appropriate function. 
  • The function overloading does it, and operator overloading is also termed as static binding or early binding.

Program

class A                                  //  base class

{

int a;

public:

void display()

{

cout<< “Class A “;

}

};

class B: public A                       //  derived class

{

int b;

public:

void display()

{

cout<<“Class B”;

}

};

In the above program, the display() function prototype is the same in both the base and derived classes. Therefore, static binding cannot be applied here. This program would run best at the run time with an appropriate selection of functions.

  • During the run time, the language’s compiler identifies various methods by identifying signatures of those methods.
  • The compiler first identifies the method signature and decides the method for a specific method call during program compilation.  
  • The execution for Compile time Polymorphism is much faster but the process is not so flexible. 

Also Read: OOPS Interview Questions

Runtime or Dynamic Polymorphism

In the Dynamic Polymorphism, a call to a single overridden method is solved during a program’s runtime. Method overriding is one of the prominent examples of Runtime Polymorphism. In this process, the overriding is done through pointers and virtual functions.

Run time polymorphism is alternatively called dynamic polymorphism. This is because a method to call is decided at run time but not compiler time. Since both methods will own the same signature and could be called using any one of the class objects, the compile-time compiler doesn’t know about this; it can only be identified during runtime.

Run time polymorphism is alternatively called dynamic polymorphism. This is because a method to call is decided at run time but not compiler time. Since both methods will own the same signature and could be called using any one of the class objects, the compile-time compiler doesn’t know about this; it can only be identified during runtime.

  • In Method Overriding, a single method is declared in a sub-class present in a parent class. The child class gains a method for implementation.
  • During Runtime Polymorphism, the class offers the specification of its own to another inherited method. This transfer between methods is achieved without modifying the parent class object codes.

Explore Our Software Development Free Courses

Important points to note about the Polymorphism concept:

  • It should have the same name, same return type, and same parameters (order, type, and length).
  • It can’t override a method that is declared static or final.
  • It can’t have a more restrictive access modifier.
  • It may have a less restrictive access modifier.
  • It should not throw a new or wider checked exception.
  • It might throw fewer, narrower, or no checked exceptions.

The overriding method of polymorphism explains that it can throw any unchecked exception, irrespective of whether the overridden method states the exception.

Explore our Popular Software Engineering Courses

Types of Polymorphism in Oops

In Object-Oriented Programming (OOPS) language, there are two types of polymorphism as below:

  1. Static Binding (or Compile time) Polymorphism, e.g., Method Overloading
  2. Dynamic Binding (or Runtime) Polymorphism, e.g., Method overriding

Source

In-Demand Software Development Skills

1. Compile Time or Static Polymorphism

With Method Overloading, static polymorphism is achieved in Object-Oriented Programming languages that allow the programmer to implement various methods. The names they use can be the same, but their parameters are different. Certain conditions are conducive for static polymorphism as below:

  •       Types of All Parameters should be different.
  •       The sequence of the Parameters can be different.
  •       The number of parameters of one method should differ from the other method.

In the static binding polymorphism, the matching type and number of arguments invoke the overloaded functions. 

  • As all of this information is available during the compile time, the compiler selects the appropriate function. 
  • The function overloading does it, and operator overloading is also termed as static binding or early binding.

Check out Java Bootcamp from upGrad

Program

class A                                  //  base class

{

int a;

public:

void display()

{

cout<< “Class A “;

}

};

class B: public A                       //  derived class

{

int b;

public:

void display()

{

cout<<“Class B”;

}

};

In the above program, the display() function prototype is the same in both the base and derived classes. Therefore, static binding cannot be applied here. This program would run best at the run time with an appropriate selection of functions.

  • During the run time, the language’s compiler identifies various methods by identifying signatures of those methods.
  • The compiler first identifies the method signature and decides the method for a specific method call during program compilation.  
  • The execution for Compile time Polymorphism is much faster but the process is not so flexible. 

Also Read: OOPS Interview Questions

Runtime or Dynamic Polymorphism

In the Dynamic Polymorphism, a call to a single overridden method is solved during a program’s runtime. Method overriding is one of the prominent examples of Runtime Polymorphism. In this process, the overriding is done through pointers and virtual functions.

  • In Method Overriding, a single method is declared in a sub-class present in a parent class. The child class gains a method for implementation.
  • During Runtime Polymorphism, the class offers the specification of its own to another inherited method. This transfer between methods is achieved without modifying the parent class object codes.

Program

 #include <iostream>    

using namespace std;    

class Animal {                                          //  base class  

    public:    

    string color = “Brown”;      

};     

class Dog: public Animal                       // inheriting Animal class.  

{      

 public:    

    string color = “Green”;      

};    

int main(void) {    

     Animal d= Dog();      

    cout<<d.color;     

}    

Output:

Brown 

  • In the Run time polymorphism, the object’s method is invoked at the run time instead of compile time. 
  • It is made possible by method overriding, which is also coined as dynamic binding or late binding. 
  • The process of dynamic polymorphism is comparatively slower but flexible than compile-time polymorphism.

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?

Ads of upGrad blog

 

Differences B/W Compile-Time and Run-Time Polymorphism 

 Compile-Time PolymorphismRun-Time Polymorphism
Invoking of FunctionThe function is invoked at the compile time.The function is invoked at the run time.
Common TermsIt is known as overloading, early binding, and static binding.It is known as overriding, late binding, and dynamic binding.
Method Name and ParametersIn Overloading, more than one method has the same name but with a different number or type of parameters.In Overriding, more than one method has the same name, number, and type of parameters.
CarriersIt is achieved with function and operator overloading.It is achieved with virtual functions and pointers.
Execution TimeIt executes faster than run-time polymorphism at the compile time.It executes slower than compile-time polymorphism at the run time.
FlexibilityIt is less flexible as everything executes at the compile time.It is more flexible as everything executes at the run time.

Read our Popular Articles related to Software Development

Final Words

Polymorphism is the must learn concepts of OOPs as it offers several advantages while programming. With Polymorphism, the user can remodel the tested classes and codes. It is useful in extending the programming by itself. It also allows the user to store multiple different type variables such as double, Float, Int, or Long in a single variable to make it simpler to search and implement them. 

If you’re interested to learn more about OOPs, full-stack software development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1What is an object in Object-Oriented Programming (OOP)?

In object-oriented programming, the concept of an object is the primary aspect that developers think of while designing a program. An object is essentially the unit of code that is derived eventually from this process. Every object is correlated to a generic class of the object. Many generic classes are defined in the library so that each corresponding object of the class can share the specific class features, and developers can reuse the definition of the class while writing the code. So, each object is like an instance of a particular class or subclass. It shares the same model, features, properties, methods, procedures, and variables.

2How is an object different from a class?

A class can be considered as a template or blueprint from which you can create objects. Objects are instances of a class that executes in the machine. Objects are real-world physical entities, whereas a class is a logical collection of similar objects. Developers can create as many objects as needed, but class is declared only once. Class does not occupy any memory when it is created, whereas memory is allocated as soon as an object is created. Objects can be declared or created in many ways using different keywords (based on the programming language). But class can be declared and defined in one way only.

3What are the essential features of object-oriented programming?

There are five essential or key features of object-oriented programming – classes and objects, inheritance, polymorphism, data abstraction, and encapsulation. Classes are datatypes defined by the users and form the primary building blocks of object-oriented programming. Objects are real-life entities that are instances of a particular class. Inheritance is the ability of one class to inherit the properties of another base class. Polymorphism facilitates using the same function with different aliases. Encapsulation and abstraction enable the simplicity of coding for developers where they only interact with a subset of an object's overall attributes, i.e., only what is essentially required.

Explore Free Courses

Suggested Blogs

Java Free Online Course with Certification [2023]
52351
The PYPL Popularity of Programming Language Index maintains that Java is the second most popular programming language in the world, after Python.  Alt
Read More

by Rohan Vats

20 Sep 2023

Salesforce Developer Salary in India in 2023 [For Freshers &#038; Experienced]
900011
Wondering what is the range of salesforce salary in India? Businesses thrive because of customers. It does not matter whether the operations are B2B
Read More

by Rohan Vats

20 Sep 2023

Literals In Java: Types of Literals in Java [With Examples]
2962
Summary: In this article, you will learn about Literals in Java. Literals in Java Integral Literals Floating-Point Literals Char Literals String Lit
Read More

by Rohan Vats

17 Sep 2023

Web Developer Salary in India in 2023 [For Freshers &#038; Experienced]
899511
Wondering what is the range of Web Developer Salary in India? World Wide Web is fascinating. Even though it has been around for decades, the idea tha
Read More

by Rohan Vats

17 Sep 2023

Top 20 Project Ideas in C++ For Beginners [2023]
169219
Summary: In this article, you will learn the top project ideas in C++. Take a glimpse below Security Systems Car Rental System Dating Applications E
Read More

by Rohan Vats

14 Sep 2023

Top 20 Trending Android Project Ideas &#038; Topics For Beginners [2023]
191927
Summary: In this article, you will learn the top 20 trending android project ideas & topics. Take a glimpse below. Android-based Function Gener
Read More

by Rohan Vats

13 Sep 2023

14 Exciting PHP Project Ideas &#038; Topics For Beginners [2023]
170648
Summary: In this article, you will learn about 14 exciting PHP project ideas. Build a Clothes Recommendation System Customer Relationship Management
Read More

by Rohan Vats

13 Sep 2023

16 Exciting Javascript Project Ideas &#038; Topics For Beginners [2023]
48982
JavaScript bridges the gap between the material and virtual worlds in the ever-converging worlds of technology and reality. JavaScript has become a vi
Read More

by Rohan Vats

12 Sep 2023

9 Exciting DBMS Project Ideas &#038; Topics For Beginners [2023]
228132
Do you want to work on database projects but don’t know where to start? Then you’ve come to the right place. In today’s article, we’ll discuss some of
Read More

by Rohan Vats

12 Sep 2023

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