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

Polymorphism in OOP: What is It, Its Types, Examples, Benefits, & More

By Rohan Vats

Updated on Feb 13, 2025 | 16 min read

Share:

You might be searching for ways to keep your code flexible without sacrificing clarity. Polymorphism in OOP can help with that. Think about a single function in a drawing program that knows how to draw circles, squares, or triangles. That function’s name stays the same, but the code behind it changes to match each shape. Polymorphism follows this pattern in code: you write a single interface, and it adapts to new requirements.

In this blog, you will explore how polymorphism works, learn about its types (compile-time and runtime) across multiple programming languages, compare their differences, and see real-world examples that bring the concept to life.

What is PolyMorphism in OOPS, and Why is it Important?

Polymorphism in OOP (object-oriented programming) is the ability for one reference or interface to represent different forms in your code. This feature makes it possible to handle various objects as if they share the same behavior, which creates adaptable programs that respond to new requirements without major rewrites.

You can better understand polymorphism in OOPS with example listed below:

  • A single shape function can handle different shapes, such as circles, squares, or triangles, using the same method name.
  • One communication method can route to different destinations while keeping the same call signature.

Below is a snippet that demonstrates polymorphism in Java. Here is what happens in the code:

  • You have a parent class called Shape that offers a draw() method.
  • Two child classes named Circle and Square override draw().
  • When you call draw() on a Shape reference, the result depends on the actual object type.
class Shape {
    void draw() {
        System.out.println("Drawing a generic shape");
    }
}

class Circle extends Shape {
    @Override
    void draw() {
        System.out.println("Drawing a circle");
    }
}

class Square extends Shape {
    @Override
    void draw() {
        System.out.println("Drawing a square");
    }
}

public class Main {
    public static void main(String[] args) {
        Shape shape1 = new Circle();
        Shape shape2 = new Square();

        shape1.draw();
        shape2.draw();
    }
}

Output: 

Drawing a circle
Drawing a square

This output appears because shape1 refers to a Circle and shape2 refers to a Square. Each call to draw() matches the actual class, which is why you see different results.

Also Read: Understanding Virtual Functions in Java: From Interfaces to Runtime Polymorphism

What is the Importance of Polymorphism in OOP?

Polymorphism is vital for true object-oriented status because it allows different objects to share the same interface while keeping their own special behaviors.

You can explore its main benefits below:

  • Allows Full OOP: Languages that skip polymorphism become object-based rather than object-oriented, so polymorphism is a foundational piece of the OOP model.
  • Encourages Code Reuse: You rely on a single method name for many classes instead of defining separate names for each one.
  • Supports Growth: You can add new subclasses without overhauling existing methods, which keeps your work neat.
  • Keeps Code OrganizedInstead of juggling many special cases, you focus on a parent class or interface.

What are the Two Types of Polymorphism in OOP? Learn Polymorphism in OOPS With Examples

You may encounter situations where the same action must adapt in distinct ways. Polymorphism addresses this by splitting into two categories: compile-time and runtime. 

Compile-time polymorphism resolves decisions when you compile the code, often using method overloading or operator overloading. Runtime polymorphism, on the other hand, finalizes those decisions as the program runs commonly through method overriding. 

Exploring these approaches will help you build adaptable systems that handle changing requirements without clutter.

What is Compile-time Polymorphism in OOP?

Compile-time polymorphism, also known as static polymorphism or early binding, involves choosing the method to run when you compile your code. This choice depends on differences in parameters or operator definitions so the compiler knows exactly which version to call. 

You get a predictable structure that keeps development clear and avoids guesswork when your program runs.

Method overloading is the most common example of compile-time polymorphism. You write multiple methods with the same name but vary their parameters by type, number, or order. This approach helps you reduce extra names in your code and makes your work more concise. 

Another way to achieve compile-time polymorphism is operator overloading, where you redefine operators like + or - to handle user-defined data. Although each language has its own syntax for this, the goal remains the same: let your code handle multiple input types without creating completely new functions.

Below are several examples that show compile-time polymorphism in OOPS in action.

Example 1: Compile-time Polymorphism in Java Using Method Overloading

This example uses method overloading. It shows how the same method name can handle different numbers of parameters. The compiler selects the appropriate version at compile time.

  • The Calculator class contains multiple add() methods.
  • One version handles two integer parameters.
  • Another version handles three integer parameters.
class Calculator {
    int add(int a, int b) {
        return a + b;
    }

    int add(int a, int b, int c) {
        return a + b + c;
    }
}

public class Main {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        System.out.println(calc.add(5, 10));
        System.out.println(calc.add(2, 3, 4));
    }
}

Output:

15
9

The output shows 15 for the two-argument call and 9 for the three-argument call. Each call matches a different add() method during compilation.

Example 2: Compile-time Polymorphism in C++ Using Method Overloading
This example also uses method overloading. It demonstrates how the same function name handles different parameters. The compiler decides which function to run based on the signature.

  • MathOps class defines multiple multiply() methods.
  • One version accepts two parameters.
  • Another version accepts three parameters.
#include <iostream>
using namespace std;

class MathOps {
public:
    int multiply(int x, int y) {
        return x * y;
    }

    int multiply(int x, int y, int z) {
        return x * y * z;
    }
};

int main() {
    MathOps ops;
    cout << ops.multiply(3, 4) << endl;
    cout << ops.multiply(2, 5, 2) << endl;
    return 0;
}

Output: 

12
20

The first call matches the two-parameter version and produces 12, while the second call matches the three-parameter version and yields 20.

Also Read: Function Overriding in C++ [Function Overloading vs Overriding with Examples]

Example 3: Compile-time Polymorphism in Python Using Operator Overloading
This example uses operator overloading. It modifies the + operator so that it can add objects of a custom class. The correct behavior is bound at compile time based on how Python handles the __add__ method.

  • Distance class redefines the + operator with __add__.
  • Each Distance object stores a numeric value in meters.
  • When two Distance objects use +, the method returns a new Distance with the combined total.
class Distance:
    def __init__(self, meters):
        self.meters = meters

    def __add__(self, other):
        return Distance(self.meters + other.meters)

    def display(self):
        print(f"{self.meters} meters")

d1 = Distance(5)
d2 = Distance(10)
d3 = d1 + d2
d3.display()

Output: 

15 meters

The output is 15 meters because the code adds the numeric parts from both objects and returns a new Distance instance.

Also Read: What is Polymorphism in Python? Polymorphism Explained with Examples

Example 4: Compile-time Polymorphism in Perl Using Operator Overloading
This example also showcases operator overloading. It customizes the + operator for a Complex class. Perl decides how to apply this operator at compile time when it detects + between Complex objects.

  • Complex package redefines the + operator through an add subroutine.
  • The constructor stores real and imaginary parts.
  • When two Complex objects use +, it returns a new Complex with the sum of both parts.
{
    package Complex;
    use overload '+' => \&add;

    sub new {
        my ($class, $r, $i) = @_;
        my $self = { real => $r, imag => $i };
        bless $self, $class;
        return $self;
    }

    sub add {
        my ($c1, $c2) = @_;
        return Complex->new($c1->{real} + $c2->{real},
                            $c1->{imag} + $c2->{imag});
    }

    sub show {
        my ($self) = @_;
        print "$self->{real} + $self->{imag}i\n";
    }
}

my $n1 = Complex->new(2, 3);
my $n2 = Complex->new(4, 5);
my $sum = $n1 + $n2;
$sum->show();

Output:

6 + 8i

The output appears because the add subroutine sums up the real and imaginary parts and prints them in a + bi form. 

What is Runtime Polymorphism in OOP? 

Runtime polymorphism, also referred to as dynamic binding or late binding, determines which method runs while your application is active. This approach often involves method overriding, where a subclass replaces or enhances a method inherited from its superclass. 

The actual method that executes depends on the underlying object type rather than the reference type. This allows you to introduce new behavior in child classes without modifying the original parent class directly, although it can bring extra overhead because each call is resolved at runtime.

Method overriding occurs when a child class provides its own version of a method that already exists in the parent class. The child class method shares the same signature but includes different logic. If you call this method using a reference of the parent type, the child’s overridden method will run if the actual object is from the child class.

Take a look at the following examples to see runtime polymorphism at work in four different languages.

Example 1: Runtime Polymorphism in Java Using Method Overriding

Below is a small program that shows how a child class can override a parent class method at runtime. It revolves around a Device hierarchy.

  • The Device class has a start() method.
  • Mobile class overrides start().
  • A reference of type Device points to a Mobile object.
class Device {
    void start() {
        System.out.println("Starting a generic device");
    }
}

class Mobile extends Device {
    @Override
    void start() {
        System.out.println("Switching on the mobile");
    }
}

public class Main {
    public static void main(String[] args) {
        Device device = new Mobile();
        device.start();
    }
}

Output:

Switching on the mobile

The output shows the child class method in action. Even though the reference is declared as Device, the actual object is Mobile, so the overridden start() method is used.

Example 2: Runtime Polymorphism in C++ Using Method Overriding

This example focuses on a vehicle hierarchy. A Vehicle class has a move() method, and two subclasses override it to meet their needs.

  • The Vehicle class defines a move() function.
  • Car and Bike each offer their own version of move().
  • A pointer to Vehicle can point to either Car or Bike.
#include <iostream>
using namespace std;

class Vehicle {
public:
    virtual void move() {
        cout << "Vehicle is moving in a general way" << endl;
    }
};

class Car : public Vehicle {
public:
    void move() override {
        cout << "Car is driving on the road" << endl;
    }
};

class Bike : public Vehicle {
public:
    void move() override {
        cout << "Bike is cycling down the path" << endl;
    }
};

int main() {
    Vehicle* v1 = new Car();
    Vehicle* v2 = new Bike();

    v1->move();
    v2->move();

    delete v1;
    delete v2;
    return 0;
}

Output:

Car is driving on the road
Bike is cycling down the path

The output confirms that each call to move() uses the method of the actual object. The pointer’s declared type is Vehicle*, but the real behavior depends on whether it points to a Car or Bike.

Example 3: Runtime Polymorphism in Python Using Method Overriding

This is a classic example of method overriding in Python. Here, a parent class called Book includes a method named read(). Two subclasses override this method with specific content.

  • Book has a basic read() method.
  • EBook and PhysicalBook each implement their own version.
  • A single reference calls read(), and Python checks which subclass is in use.

When my_book.read() is called, Python looks at the actual type of my_book.

class Book:
    def read(self):
        print("Reading a general book")

class EBook(Book):
    def read(self):
        print("Reading an eBook on a device")

class PhysicalBook(Book):
    def read(self):
        print("Reading a physical copy with paper pages")

def start_reading(book):
    book.read()

ebook = EBook()
pbook = PhysicalBook()

start_reading(ebook)
start_reading(pbook)

Output:

Reading an eBook on a device
Reading a physical copy with paper pages

The function start_reading(book) runs the overridden method of either EBook or PhysicalBook, depending on which object is passed.

Example 4: Runtime Polymorphism in Perl Using Method Overriding

Below is a scenario involving different payment methods. A Payment parent class has a method named pay(), and child classes override it to provide unique payment styles.

  • Payment package defines a pay() subroutine with a generic message.
  • CreditPayment and CashPayment override pay().
  • Payment reference points to objects of these child classes.

The actual subroutine call depends on the object’s real package.

{
    package Payment;
    sub new {
        my $class = shift;
        bless {}, $class;
    }

    sub pay {
        print "Processing a generic payment\n";
    }
}

{
    package CreditPayment;
    our @ISA = qw(Payment);
    sub pay {
        print "Paying with credit\n";
    }
}

{
    package CashPayment;
    our @ISA = qw(Payment);
    sub pay {
        print "Paying with cash\n";
    }
}

my $pay1 = CreditPayment->new();
my $pay2 = CashPayment->new();

my $payment_ref;

$payment_ref = $pay1;
$payment_ref->pay();

$payment_ref = $pay2;
$payment_ref->pay();

Output: 

Paying with credit
Paying with cash

The calls to $payment_ref->pay() trigger the CreditPayment version first, followed by the CashPayment version. Perl looks up the object's actual package instead of relying on the declared parent class.

For in-depth knowledge, you can also check out upGrad's free tutorial, Overloading vs Overriding in Java.

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?

 

Compile-time Polymorphism vs Runtime Polymorphism: Key Differences

You might wonder how the specific timing of method selection affects your program’s structure and efficiency. Compile-time polymorphism fixes which method will run before execution begins, whereas runtime polymorphism decides the method call during the program’s operation. 

Each approach offers distinct benefits in terms of speed, flexibility, and how child classes can refine behavior from a parent class.

Here is a table that highlights several key differences:

Aspect

Compile-time Polymorphism

Runtime Polymorphism

Binding Time Occurs at compilation, so the method to execute is fixed before execution. Happens during execution, where the actual object decides which method runs.
Primary Mechanism Typically relies on overloading or operator redefinition. Uses overriding, where a child class redefines a parent class method.
Inheritance Does not require inheritance, though both can coexist in the same project. Relies on an inheritance chain, allowing children to supply tailored methods.
Performance Often faster, since the compiler resolves calls in advance. May be slower because each method call is resolved at runtime.
Flexibility Less flexible, as behavior is tied to signatures chosen at compile time. More flexible, because the object type at runtime dictates which method is used.
Use Cases Suited to handling different parameter lists or operator inputs under one method name. Best for scenarios where child classes must alter or extend a shared method.
Maintenance Straightforward, but adding more overloads can clutter a class if many forms are needed. Simplifies expansion by letting new subclasses override the parent’s methods.
Type Checking The compiler enforces correctness based on known parameter types or operator definitions. The system checks the object type during execution, so mismatches surface at runtime.

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

What are the Advantages of Polymorphism in OOP?

Polymorphism in OOPS lets different classes share consistent structures while still keeping unique implementations. This approach creates stronger software designs and opens the door to simpler expansions. It also lessens the need to craft entirely new function sets whenever your requirements change.

Below are some of the most noteworthy advantages:

  • Enables Code Reuse: You can share method or class structures across various parts of your application.
  • Simplifies Maintenance: You spend less time updating multiple versions of the same function, which helps keep your project organized.
  • Reduces Repetitive Code: You rely on a single interface for related tasks instead of defining separate functions that do similar work.
  • Enhances Flexibility: You can introduce new implementations at any point without redesigning existing parts.
  • Makes Collaboration Easier: Your team can understand and modify unified interfaces with fewer naming conflicts or redundant definitions.
  • Supports Growth: Adding new object types becomes quick since you can extend existing structures.
  • Offers a Cleaner Structure: Unifying methods under shared names keeps code uncluttered and more readable.
  • Speeds Up Debugging: Consistent method naming and well-defined hierarchies help you trace issues faster.

What are the Disadvantages of Polymorphism in OOP?

Polymorphism can introduce hidden complexities that affect performance and code organization. While it promotes flexible designs, it also creates potential pitfalls if class hierarchies or overridden methods are not handled carefully.

Below are some common drawbacks:

  • Performance Overhead: Late binding in runtime polymorphism requires extra lookups, which can slow execution in resource-intensive applications.
  • Fragile Base Class Issue: Minor changes in a parent class might break child classes that rely on specific methods or fields, making updates risky.
  • Downcasting Pitfalls: Casting a parent reference to a child type can fail if the object does not match the expected subclass, leading to runtime errors.
  • Complex Debugging: Polymorphic calls can make it harder to track down the actual method that caused a bug, especially in deep inheritance chains.
  • Excessive Overloading: In compile-time polymorphism, creating many overloaded methods can clutter a class, reducing clarity.
  • Confusion in Large Teams: Different override or overload decisions may cause misunderstandings if team members expect the same name to behave consistently.

What are the Real-life Examples of Polymorphism in OOPS?

You may encounter scenarios where one action takes many forms based on the situation. This versatility appears everywhere, from daily routines to business operations. Polymorphism mirrors these real-world patterns by allowing a single interface to produce unique outcomes.

Here are some everyday examples of polymorphism in OOP that illustrate this principle:

  • One Person, Many Roles: An individual can be a sibling, a coach, and an employee at different times. Each role demands distinct responsibilities, yet the same person fulfills them.
  • Payment Options at the Store: A single checkout system might process cash, cards, or digital wallets. Even though the interface is the same, the system adjusts to each payment method.
  • A Smartphone’s Camera and Phone Functions: You use one device for calls, photos, or music. The interface looks similar, but the underlying operation changes based on what you choose to do.
  • An All-Purpose Kitchen Appliance: A single machine may act as a blender, grinder, or juicer. The settings differ, but the outer controls stay consistent.
  • An Online Delivery Service: The interface handles groceries, medicines, and electronics through the same order page. Each category follows distinct dispatch protocols, yet the system processes all requests seamlessly.

What are the Real-world Uses of Polymorphism Across Various Industries?

Many large companies and independent teams often rely on polymorphism to keep their systems structured while allowing new features to fit in quickly. It appears in fields ranging from online retail that deals with various payment methods to security platforms that validate different login procedures. This approach lowers the need for complete rewrites and maintains a cohesive style when developers add new functions.

Below is a table that highlights several industries and the ways polymorphism shapes their solutions:

Industry

Use Case

Why Polymorphism Help?

E-commerce Different shipping options, payment methods, and user roles Lets you handle various actions (shipping, payment) under shared interfaces.
Healthcare Patient management with diverse record types Simplifies additions of new record categories without changing established procedures.
Gaming Multiple character classes in role-playing titles Lets each class override shared methods (attack, defend) for unique abilities.
Finance Various transaction types like checks, cards, or e-wallets Allows each transaction type to extend a common interface and apply specific logic.
Automotive A single diagnostic system for different car models Lets each model override standard checks without overhauling the entire application.
Education A unified portal for courses, labs, and extracurriculars Makes it easy to add new sections or modules under one central structure.
IT and software Frameworks or microservices that share common interfaces Enables teams to override shared methods, avoiding repeated code in large architectures.

Conclusion

You’ve seen how polymorphism in OOP merges code structure with adaptability, letting you unify different behaviors under a single interface. By splitting it into compile-time and runtime forms, you keep your methods efficient and open to change. 

Polymorphism promotes cleaner designs, easier updates, and broad real-world uses across industries like healthcare, e-commerce, and IT. If you want to strengthen your skills further, you can enroll in upGrad's free course on Java Object-oriented Programming.

With the right training and practice, you’ll build software that stays flexible when requirements shift — setting the stage for lasting success in your development journey.

Related Blogs and Tutorials:

Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.

Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.

Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.

Frequently Asked Questions (FAQs)

1. What is an example of polymorphism?

2. What is polymorphism in OOP in Python?

3. What is polymorphism in C++?

4. Is polymorphism inheritance?

5. What is polymorphism in Java?

6. What is overloading and overriding?

7. Why is polymorphism used?

8. What is the difference between polymorphism and encapsulation?

9. What is a real life example of polymorphism?

10. Is polymorphism abstraction?

11. Is polymorphism overriding?

Rohan Vats

419 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

Suggested Blogs