- Blog Categories
- Software Development
- Data Science
- AI/ML
- Marketing
- General
- MBA
- Management
- Legal
- Software Development Projects and Ideas
- 12 Computer Science Project Ideas
- 28 Beginner Software Projects
- Top 10 Engineering Project Ideas
- Top 10 Easy Final Year Projects
- Top 10 Mini Projects for Engineers
- 25 Best Django Project Ideas
- Top 20 MERN Stack Project Ideas
- Top 12 Real Time Projects
- Top 6 Major CSE Projects
- 12 Robotics Projects for All Levels
- Java Programming Concepts
- Abstract Class in Java and Methods
- Constructor Overloading in Java
- StringBuffer vs StringBuilder
- Java Identifiers: Syntax & Examples
- Types of Variables in Java Explained
- Composition in Java: Examples
- Append in Java: Implementation
- Loose Coupling vs Tight Coupling
- Integrity Constraints in DBMS
- Different Types of Operators Explained
- Career and Interview Preparation in IT
- Top 14 IT Courses for Jobs
- Top 20 Highest Paying Languages
- 23 Top CS Interview Q&A
- Best IT Jobs without Coding
- Software Engineer Salary in India
- 44 Agile Methodology Interview Q&A
- 10 Software Engineering Challenges
- Top 15 Tech's Daily Life Impact
- 10 Best Backends for React
- Cloud Computing Reference Models
- Web Development and Security
- Find Installed NPM Version
- Install Specific NPM Package Version
- Make API Calls in Angular
- Install Bootstrap in Angular
- Use Axios in React: Guide
- StrictMode in React: Usage
- 75 Cyber Security Research Topics
- Top 7 Languages for Ethical Hacking
- Top 20 Docker Commands
- Advantages of OOP
- Data Science Projects and Applications
- 42 Python Project Ideas for Beginners
- 13 Data Science Project Ideas
- 13 Data Structure Project Ideas
- 12 Real-World Python Applications
- Python Banking Project
- Data Science Course Eligibility
- Association Rule Mining Overview
- Cluster Analysis in Data Mining
- Classification in Data Mining
- KDD Process in Data Mining
- Data Structures and Algorithms
- Binary Tree Types Explained
- Binary Search Algorithm
- Sorting in Data Structure
- Binary Tree in Data Structure
- Binary Tree vs Binary Search Tree
- Recursion in Data Structure
- Data Structure Search Methods: Explained
- Binary Tree Interview Q&A
- Linear vs Binary Search
- Priority Queue Overview
- Python Programming and Tools
- Top 30 Python Pattern Programs
- List vs Tuple
- Python Free Online Course
- Method Overriding in Python
- Top 21 Python Developer Skills
- Reverse a Number in Python
- Switch Case Functions in Python
- Info Retrieval System Overview
- Reverse a Number in Python
- Real-World Python Applications
- Data Science Careers and Comparisons
- Data Analyst Salary in India
- Data Scientist Salary in India
- Free Excel Certification Course
- Actuary Salary in India
- Data Analyst Interview Guide
- Pandas Interview Guide
- Tableau Filters Explained
- Data Mining Techniques Overview
- Data Analytics Lifecycle Phases
- Data Science Vs Analytics Comparison
- Artificial Intelligence and Machine Learning Projects
- Exciting IoT Project Ideas
- 16 Exciting AI Project Ideas
- 45+ Interesting ML Project Ideas
- Exciting Deep Learning Projects
- 12 Intriguing Linear Regression Projects
- 13 Neural Network Projects
- 5 Exciting Image Processing Projects
- Top 8 Thrilling AWS Projects
- 12 Engaging AI Projects in Python
- NLP Projects for Beginners
- Concepts and Algorithms in AIML
- Basic CNN Architecture Explained
- 6 Types of Regression Models
- Data Preprocessing Steps
- Bagging vs Boosting in ML
- Multinomial Naive Bayes Overview
- Bayesian Network Example
- Bayes Theorem Guide
- Top 10 Dimensionality Reduction Techniques
- Neural Network Step-by-Step Guide
- Technical Guides and Comparisons
- Make a Chatbot in Python
- Compute Square Roots in Python
- Permutation vs Combination
- Image Segmentation Techniques
- Generative AI vs Traditional AI
- AI vs Human Intelligence
- Random Forest vs Decision Tree
- Neural Network Overview
- Perceptron Learning Algorithm
- Selection Sort Algorithm
- Career and Practical Applications in AIML
- AI Salary in India Overview
- Biological Neural Network Basics
- Top 10 AI Challenges
- Production System in AI
- Top 8 Raspberry Pi Alternatives
- Top 8 Open Source Projects
- 14 Raspberry Pi Project Ideas
- 15 MATLAB Project Ideas
- Top 10 Python NLP Libraries
- Naive Bayes Explained
- Digital Marketing Projects and Strategies
- 10 Best Digital Marketing Projects
- 17 Fun Social Media Projects
- Top 6 SEO Project Ideas
- Digital Marketing Case Studies
- Coca-Cola Marketing Strategy
- Nestle Marketing Strategy Analysis
- Zomato Marketing Strategy
- Monetize Instagram Guide
- Become a Successful Instagram Influencer
- 8 Best Lead Generation Techniques
- Digital Marketing Careers and Salaries
- Digital Marketing Salary in India
- Top 10 Highest Paying Marketing Jobs
- Highest Paying Digital Marketing Jobs
- SEO Salary in India
- Content Writer Salary Guide
- Digital Marketing Executive Roles
- Career in Digital Marketing Guide
- Future of Digital Marketing
- MBA in Digital Marketing Overview
- Digital Marketing Techniques and Channels
- 9 Types of Digital Marketing Channels
- Top 10 Benefits of Marketing Branding
- 100 Best YouTube Channel Ideas
- YouTube Earnings in India
- 7 Reasons to Study Digital Marketing
- Top 10 Digital Marketing Objectives
- 10 Best Digital Marketing Blogs
- Top 5 Industries Using Digital Marketing
- Growth of Digital Marketing in India
- Top Career Options in Marketing
- Interview Preparation and Skills
- 73 Google Analytics Interview Q&A
- 56 Social Media Marketing Q&A
- 78 Google AdWords Interview Q&A
- Top 133 SEO Interview Q&A
- 27+ Digital Marketing Q&A
- Digital Marketing Free Course
- Top 9 Skills for PPC Analysts
- Movies with Successful Social Media Campaigns
- Marketing Communication Steps
- Top 10 Reasons to Be an Affiliate Marketer
- Career Options and Paths
- Top 25 Highest Paying Jobs India
- Top 25 Highest Paying Jobs World
- Top 10 Highest Paid Commerce Job
- Career Options After 12th Arts
- Top 7 Commerce Courses Without Maths
- Top 7 Career Options After PCB
- Best Career Options for Commerce
- Career Options After 12th CS
- Top 10 Career Options After 10th
- 8 Best Career Options After BA
- Projects and Academic Pursuits
- 17 Exciting Final Year Projects
- Top 12 Commerce Project Topics
- Top 13 BCA Project Ideas
- Career Options After 12th Science
- Top 15 CS Jobs in India
- 12 Best Career Options After M.Com
- 9 Best Career Options After B.Sc
- 7 Best Career Options After BCA
- 22 Best Career Options After MCA
- 16 Top Career Options After CE
- Courses and Certifications
- 10 Best Job-Oriented Courses
- Best Online Computer Courses
- Top 15 Trending Online Courses
- Top 19 High Salary Certificate Courses
- 21 Best Programming Courses for Jobs
- What is SGPA? Convert to CGPA
- GPA to Percentage Calculator
- Highest Salary Engineering Stream
- 15 Top Career Options After Engineering
- 6 Top Career Options After BBA
- Job Market and Interview Preparation
- Why Should You Be Hired: 5 Answers
- Top 10 Future Career Options
- Top 15 Highest Paid IT Jobs India
- 5 Common Guesstimate Interview Q&A
- Average CEO Salary: Top Paid CEOs
- Career Options in Political Science
- Top 15 Highest Paying Non-IT Jobs
- Cover Letter Examples for Jobs
- Top 5 Highest Paying Freelance Jobs
- Top 10 Highest Paying Companies India
- Career Options and Paths After MBA
- 20 Best Careers After B.Com
- Career Options After MBA Marketing
- Top 14 Careers After MBA In HR
- Top 10 Highest Paying HR Jobs India
- How to Become an Investment Banker
- Career Options After MBA - High Paying
- Scope of MBA in Operations Management
- Best MBA for Working Professionals India
- MBA After BA - Is It Right For You?
- Best Online MBA Courses India
- MBA Project Ideas and Topics
- 11 Exciting MBA HR Project Ideas
- Top 15 MBA Project Ideas
- 18 Exciting MBA Marketing Projects
- MBA Project Ideas: Consumer Behavior
- What is Brand Management?
- What is Holistic Marketing?
- What is Green Marketing?
- Intro to Organizational Behavior Model
- Tech Skills Every MBA Should Learn
- Most Demanding Short Term Courses MBA
- MBA Salary, Resume, and Skills
- MBA Salary in India
- HR Salary in India
- Investment Banker Salary India
- MBA Resume Samples
- Sample SOP for MBA
- Sample SOP for Internship
- 7 Ways MBA Helps Your Career
- Must-have Skills in Sales Career
- 8 Skills MBA Helps You Improve
- Top 20+ SAP FICO Interview Q&A
- MBA Specializations and Comparative Guides
- Why MBA After B.Tech? 5 Reasons
- How to Answer 'Why MBA After Engineering?'
- Why MBA in Finance
- MBA After BSc: 10 Reasons
- Which MBA Specialization to choose?
- Top 10 MBA Specializations
- MBA vs Masters: Which to Choose?
- Benefits of MBA After CA
- 5 Steps to Management Consultant
- 37 Must-Read HR Interview Q&A
- Fundamentals and Theories of Management
- What is Management? Objectives & Functions
- Nature and Scope of Management
- Decision Making in Management
- Management Process: Definition & Functions
- Importance of Management
- What are Motivation Theories?
- Tools of Financial Statement Analysis
- Negotiation Skills: Definition & Benefits
- Career Development in HRM
- Top 20 Must-Have HRM Policies
- Project and Supply Chain Management
- Top 20 Project Management Case Studies
- 10 Innovative Supply Chain Projects
- Latest Management Project Topics
- 10 Project Management Project Ideas
- 6 Types of Supply Chain Models
- Top 10 Advantages of SCM
- Top 10 Supply Chain Books
- What is Project Description?
- Top 10 Project Management Companies
- Best Project Management Courses Online
- Salaries and Career Paths in Management
- Project Manager Salary in India
- Average Product Manager Salary India
- Supply Chain Management Salary India
- Salary After BBA in India
- PGDM Salary in India
- Top 7 Career Options in Management
- CSPO Certification Cost
- Why Choose Product Management?
- Product Management in Pharma
- Product Design in Operations Management
- Industry-Specific Management and Case Studies
- Amazon Business Case Study
- Service Delivery Manager Job
- Product Management Examples
- Product Management in Automobiles
- Product Management in Banking
- Sample SOP for Business Management
- Video Game Design Components
- Top 5 Business Courses India
- Free Management Online Course
- SCM Interview Q&A
- Fundamentals and Types of Law
- Acceptance in Contract Law
- Offer in Contract Law
- 9 Types of Evidence
- Types of Law in India
- Introduction to Contract Law
- Negotiable Instrument Act
- Corporate Tax Basics
- Intellectual Property Law
- Workmen Compensation Explained
- Lawyer vs Advocate Difference
- Law Education and Courses
- LLM Subjects & Syllabus
- Corporate Law Subjects
- LLM Course Duration
- Top 10 Online LLM Courses
- Online LLM Degree
- Step-by-Step Guide to Studying Law
- Top 5 Law Books to Read
- Why Legal Studies?
- Pursuing a Career in Law
- How to Become Lawyer in India
- Career Options and Salaries in Law
- Career Options in Law India
- Corporate Lawyer Salary India
- How To Become a Corporate Lawyer
- Career in Law: Starting, Salary
- Career Opportunities: Corporate Law
- Business Lawyer: Role & Salary Info
- Average Lawyer Salary India
- Top Career Options for Lawyers
- Types of Lawyers in India
- Steps to Become SC Lawyer in India
- Tutorials
- Software Tutorials
- C Tutorials
- Recursion in C: Fibonacci Series
- Checking String Palindromes in C
- Prime Number Program in C
- Implementing Square Root in C
- Matrix Multiplication in C
- Understanding Double Data Type
- Factorial of a Number in C
- Structure of a C Program
- Building a Calculator Program in C
- Compiling C Programs on Linux
- Java Tutorials
- Handling String Input in Java
- Determining Even and Odd Numbers
- Prime Number Checker
- Sorting a String
- User-Defined Exceptions
- Understanding the Thread Life Cycle
- Swapping Two Numbers
- Using Final Classes
- Area of a Triangle
- Skills
- Explore Skills
- Management Skills
- Software Engineering
- JavaScript
- Data Structure
- React.js
- Core Java
- Node.js
- Blockchain
- SQL
- Full stack development
- Devops
- NFT
- BigData
- Cyber Security
- Cloud Computing
- Database Design with MySQL
- Cryptocurrency
- Python
- Digital Marketings
- Advertising
- Influencer Marketing
- Performance Marketing
- Search Engine Marketing
- Email Marketing
- Content Marketing
- Social Media Marketing
- Display Advertising
- Marketing Analytics
- Web Analytics
- Affiliate Marketing
- MBA
- MBA in Finance
- MBA in HR
- MBA in Marketing
- MBA in Business Analytics
- MBA in Operations Management
- MBA in International Business
- MBA in Information Technology
- MBA in Healthcare Management
- MBA In General Management
- MBA in Agriculture
- MBA in Supply Chain Management
- MBA in Entrepreneurship
- MBA in Project Management
- Management Program
- Consumer Behaviour
- Supply Chain Management
- Financial Analytics
- Introduction to Fintech
- Introduction to HR Analytics
- Fundamentals of Communication
- Art of Effective Communication
- Introduction to Research Methodology
- Mastering Sales Technique
- Business Communication
- Fundamentals of Journalism
- Economics Masterclass
- Free Courses
- Home
- Blog
- Software Development
- Polymorphism in OOP: What is It, Its Types, Examples, Benefits, & More
Polymorphism in OOP: What is It, Its Types, Examples, Benefits, & More
Updated on Feb 13, 2025 | 16 min read
Share:
Table of Contents
- What is PolyMorphism in OOPS, and Why is it Important?
- What are the Two Types of Polymorphism in OOP? Learn Polymorphism in OOPS With Examples
- Compile-time Polymorphism vs Runtime Polymorphism: Key Differences
- What are the Advantages of Polymorphism in OOP?
- What are the Disadvantages of Polymorphism in OOP?
- What are the Real-life Examples of Polymorphism in OOPS?
- What are the Real-world Uses of Polymorphism Across Various Industries?
- Conclusion
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 Organized: Instead 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.
- A 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.
- A 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.
- A 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.
- A 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.
- A Payment package defines a pay() subroutine with a generic message.
- CreditPayment and CashPayment override pay().
- A 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.
Explore our Popular Software Engineering Courses
Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.
In-Demand Software Development Skills
Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.
Read our Popular Articles related to Software
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?
Get Free Consultation
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
Top Resources