- Blog Categories
- 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
- Gini Index for Decision Trees
- 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
- Brand Manager 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
- 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
- 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
- Search Engine Optimization
- 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
Polymorphism In OOPS: What is Polymorphism [Detailed Explanation]
Updated on 25 July, 2024
130.32K+ views
• 20 min read
Table of Contents
- Why is polymorphism used?
- Benefits of Polymorphism in OOPS:
- An Example of Polymorphism in OOPs
- Explanation
- Important concepts about Polymorphism in OOPS:
- Important points to note about the Polymorphism concept:
- Types of Polymorphism in OOPS
- Java Inheritance and Polymorphism
- Final Words
- Frequently Asked Questions (FAQs)
What is Polymorphism in OOPS?
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.
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.
Polymorphism in Java is used for the following important reasons:
Code reusability: OOPS polymorphism allows using a single interface to represent a general action across multiple classes. This means common functionality can be defined in a superclass, and subclasses can override these methods to provide their specialized implementations. This reusability reduces redundant code and makes maintenance easier.
Flexibility and extensibility: You can add new classes that implement a common interface without modifying existing code through polymorphism. This facilitates scalability and allows for easy extension of functionality by introducing new classes that conform to the existing interface.
Abstraction: Polymorphism in Java enables the use of abstract classes or interfaces to define methods without specifying their implementation details. This abstraction allows for a higher level of generalization and helps design systems based on behaviors rather than specific implementations.
Simplification of code: Polymorphism can simplify code by allowing a single method to be used for multiple different objects. This makes the code more concise, readable, and maintainable.
Run-time binding (Dynamic Binding): OOPS polymorphism allows for dynamic binding of method calls at runtime. When a method is invoked on an object, the specific implementation to be executed is decided at runtime, considering the actual object type, not the declared type. This enables flexibility in program behavior during execution.
Polymorphic behavior: It allows for polymorphic behavior, meaning that different objects can respond to the same message differently based on their specific implementations. This facilitates the handling of diverse objects in a unified manner.
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.
Defining methods in a superclass and overriding them in subclasses provides a clear and organized structure that simplifies maintenance and debugging efforts.
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.
It allows for programming various forms of code execution and facilitates the development of flexible, extensible, and maintainable codebases.
The Polymorphism feature lets programming become more resourceful and faster for code development.
Developers can build upon existing code, resulting in more efficient development cycles.
It decreases coupling and maximizes reusability to code a readable program.
Emphasizing a modular and loosely coupled design helps create more readable, maintainable, and adaptable programs.
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.
In programming, this indicates different classes can have methods with the same name but different implementations. When a method is called on an object, the specific implementation associated with that object’s class is executed.
This concept helps create more flexible and reusable code by allowing different objects to be handled through a unified interface, similar to how various life forms can share common characteristics or stages in biology. In languages like Java, polymorphism is a fundamental feature that enables code to work with different objects in a uniform way, enhancing flexibility and extensibility.
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.
- Method overloading: This occurs within a single class when multiple methods have the same name but differ in their parameters (either in the number of parameters or their types). For instance, a class might have two methods both named calculate, one accepting two integers and another accepting two doubles.
The compiler differentiates between these methods based on the parameters provided when calling the calculate method. Overloading allows a class to perform similar tasks using different parameter inputs, enhancing code readability and usability.
- Method overriding: This occurs when a method in a subclass has the same name, return type, and parameters as a method in its superclass. The subclass provides its implementation for that method. This feature allows a subclass to provide a specific implementation of a method already defined in its superclass. The method in the subclass overrides the method’s behavior in the superclass when the subclass object is used.
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.
During compile time, the code is checked for syntax errors, and if the syntax is correct, the compiler generates an executable file or bytecode (in languages like Java). The compiler also performs various optimizations to enhance the performance of the resulting program.
The output of the compile time is an executable file (in the case of compiled languages like C or C++) or bytecode (in the case of languages like Java) that contains instructions the computer’s processor can understand.
Runtime is when a program is executing and usually happens after compile time.
During runtime, the computer’s processor executes the instructions in the compiled program or bytecode. It involves memory allocation, variable assignments, method calls, and any other action specified by the program’s logic.
The output of the runtime phase is the actual behavior or results produced by the executed program based on the operations specified in the source code.
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.
To elaborate further, function overloading occurs when multiple functions within the same scope (class or namespace) have the same name but differ in their parameters (number or types of parameters). These functions may perform similar or related tasks but with different parameter inputs.
If varied parameters are used, then these functions are said to be overloaded.
Operator overloading allows operators (like +, -, *, /, etc.) to be redefined for user-defined types. It enables the use of operators with custom objects or types by specifying their behavior through specially defined functions.
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.
Methods in a class: A class serves as a blueprint or template to create objects. Methods defined within a class encapsulate the behaviors or functionalities associated with that class. These methods describe what an object of that class can do or how it can interact with other objects or the outside world.
Methods can perform various operations, such as modifying the object’s state (changing its attributes), performing calculations, interacting with other objects, or providing information about the object.
Methods in an object: When an object is created based on a class, it inherits all the methods defined in that class. These methods can be invoked or called on the object to perform specific actions associated with that object.
Each object maintains its own data set, and the methods define how that data can be accessed or manipulated for that specific instance of the class.
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:
- Static Binding (or Compile time) Polymorphism, e.g., Method Overloading
- Dynamic Binding (or Runtime) Polymorphism, e.g., Method overriding
In-Demand Software Development Skills
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).
This ensures that the overridden method is a proper replacement for the method in the superclass.
- It can’t override a method that is declared static or final.
A static method belongs to the class, not to instances, and a final method cannot be modified or overridden in subclasses.
- It can’t have a more restrictive access modifier.
For instance, if the superclass method is declared as public, the overriding method in the subclass cannot be private or protected, as this would restrict access more than the superclass allows.
- It may have a less restrictive access modifier.
If the superclass method is, for example, protected, the subclass method can be declared as public. This rule enables the subclass method to broaden the scope of visibility compared to the superclass method.
- It should not throw a new or wider checked exception.
If the superclass method throws a particular checked exception, the overridden method in the subclass can throw the same type of exception or narrower exceptions. However, it should refrain from introducing broader exceptions or entirely new types of checked exceptions.
- It might throw fewer, narrower, or no checked exceptions.
These rules ensure that the subclass method doesn’t broaden the exceptions thrown beyond what the superclass method allows. Instead, it can narrow down the exceptions or not throw any checked exceptions, maintaining compatibility and flexibility in exception handling.
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:
- Static Binding (or Compile time) Polymorphism, e.g., Method Overloading
- Dynamic Binding (or Runtime) Polymorphism, e.g., Method overriding
In-Demand Software Development Skills
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?
Differences B/W Compile-Time and Run-Time Polymorphism
Compile-Time Polymorphism | Run-Time Polymorphism | |
Invoking of Function | The function is invoked at the compile time. | The function is invoked at the run time. |
Common Terms | It is known as overloading, early binding, and static binding. | It is known as overriding, late binding, and dynamic binding. |
Method Name and Parameters | In 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. |
Carriers | It is achieved with function and operator overloading. | It is achieved with virtual functions and pointers. |
Execution Time | It executes faster than run-time polymorphism at the compile time. | It executes slower than compile-time polymorphism at the run time. |
Flexibility | It 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
Java Inheritance and Polymorphism
In Java, inheritance and polymorphism are fundamental concepts that play a crucial role in object-oriented programming (OOP).
Inheritance:
Java supports inheritance, allowing one class (subclass or child class) to inherit attributes and behaviors (methods) from another class (superclass or parent class).
Syntax:
class Subclass extends Superclass { ... }
The subclass inherits the properties and methods of the superclass and can also have its own additional properties and methods.
It promotes code reuse and establishes an “is-a” relationship between classes, where a subclass “is a” type of its superclass.
Example:
// Superclass
class Animal {
public void makeSound() {
System.out.println("Some sound");
}
}
// Subclass inheriting from Animal
class Tiger extends Animal {
public void wagTail() {
System.out.println("Pouncing");
}
}
Polymorphism:
Polymorphism in Java allows objects belonging to different classes through method overriding to be treated as objects of a common superclass. It enables code to work with objects of various types using a shared interface, allowing for flexibility and extensibility. Polymorphism is attained via method overriding, wherein a derived class offers its own customized implementation for a method already defined in its parent class.
Example:
class Animal {
public void makeSound() {
System.out.println("Some sound");
}
}
class Tiger extends Animal {
@Override
public void makeSound() {
System.out.println("Roar!");
}
}
Here, if you have an Animal reference pointing to a Tiger object, calling the makeSound() method will execute the overridden method specific to the Tiger class at runtime, demonstrating polymorphic behavior.
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.
Frequently Asked Questions (FAQs)
1. What 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.
2. How 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.
3. What 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.
Did you find this article helpful?
Our Trending Courses 3
Master of Science in Computer Science Master of Design in User Experience DBA Doctorate in Technology (Computer Science)Our Trending Skill 16
Javascript Courses Node.js Courses Blockchain Courses SQL Courses Core Java Courses Full Stack Development Courses Big Data Courses DevOps Courses Data Structures Courses NFT Courses Cyber Security Courses React JS Courses Cloud Computing Courses Database Design Courses Python Courses Cryptocurrency CoursesGet Free Counsultation
By clicking "Submit" you Agree toupGrad's Terms & Conditions