Polymorphism is the primary asset of object-oriented programming. As polymorphism is so important, languages that do not support it cannot legitimately claim to be object-oriented languages. Object-based languages have classes but not polymorphism. It is consequently necessary for an object-oriented programming language. Let’s explore the polymorphism component of OOP and learn about its many varieties, benefits, and drawbacks.
What is Polymorphism?
Something’s capacity to assume multiple forms is known as polymorphism. Programming languages that include this feature allow us to generate class objects with identical names and distinct behaviors, even when they are derived from the same parent class. In Object-Oriented Programming, variables and methods that use a single interface with various underlying forms also display polymorphic behavior. This improves the language’s capacity to repeatedly utilize the same lines of code.
In addition to allowing for code reuse, polymorphism lets variables of several data types, like int, float, long, and double, be stored under a single variable name. In a similar vein, we can combine basic abstractions to create more potent and complicated ones that facilitate code debugging.
Types of Polymorphism
OOP languages’ polymorphism can be broadly divided into two categories: compile-time and runtime.
Compile-time polymorphism: Method overloading, in which functions have the same name but differ in the number, kinds, or sequence of arguments they take, is used to achieve compile-time polymorphism.
Compile-time polymorphism allows developers to handle multiple cases with a single operation, saving them from having to design distinct methods for each scenario. This implies that methods sharing the same name function differently in different situations based on the data provided. Additionally, code readability is increased when function names are the same.
Related Article: Object-oriented Programming in Python: Concepts and Techniques.
Let’s take an example where we wish to develop a program that can add any number of arguments to a given set of numbers.
Example
public class MethodOverloading {
public static void add(int a, int b)
{
int sum = a + b;
System.out.println(sum);
}
public static void add(int a, int b, int c)
{
int sum = a + b + c;
System.out.println(sum);
}
public static void add(double a, double b)
{
double sum = a + b;
System.out.println(sum);
}
public static void main(String[] args) {
add(10,10);
add(10,10,10);
add(10.2,-3.1);
}
}
Output:
20
30
7.1
Runtime Polymorphism: Dynamic polymorphism is achieved by overriding methods and using virtual functions that are determined at runtime; inheritance is taken into consideration during implementation. A subclass’s method needs to be the same as the one defined in the parent class for method overriding to occur. In this situation, a call to a single overridden method is handled at runtime when, let’s say, a Java virtual machine (JVM) recognizes a suitable method to execute upon assigning a subclass to its parent form. Since the subclass can override every method specified in the parent class, this intervention is crucial. Explore what are object methods in Java.
class ParentClass {
public void overrideMethod(){
System.out.println(“This method is overridden.”);
}
}
public class ChildClass extends ParentClass{
public void overrideMethod(){
System.out.println(“This method will override.”);
}
public static void main(String[] args) {
ParentClass obj = new ChildClass();
obj.overrideMethod();
}
}
Output
This method will override
Every time an overridden method is called through a parent class reference, the JVM detects the object type, which controls which method will be performed during runtime. The code might, for example, resemble this:
ParentClass obj = new ParentClass();
obj.overrideMethod();
ChildClass obj = new ChildClass();
obj.overrideMethod();
ParentClass obj = new ChildClass();
obj.overrideMethod();
Related article: Why should you learn Python?
Examples of Polymorphism in OOPs
- A person plays the parts of a father at home, a worker at work, and a mall shopper.
- When distinct individuals enter, a security guard stationed outside the organization acts differently. He acts one way when the boss walks up and differently when the staff shows up.
- The girl ends their amorous relationship with the word “friendship,” just as the boy begins his. The girl says we are going to be best friends for eternity.
- Assume that you behave as a student in the classroom, a consumer in a store, and a son or daughter at home. Here, we may see a single individual acting in multiple ways.
Assume that one person is seen here, functioning in several capacities: in a classroom, you behave like a student; in a store, you act like a consumer; and at home, you act like a son or daughter. Explore various types of Java applications.
Why is polymorphism used?
The concept of polymorphism allows you to do a single task in several ways. One interface specification allows you to leverage several implementations. The term “polymorphism” refers to polymorphism, in which “morphs” stands for forms and “poly” for many. It therefore denotes a range of shapes. Discover what the latest IT salary in India is for freshers.
- The ability of polymorphism to expand and leverage older programs is one of its primary benefits. This saves the developers’ time and effort.
- Many other types of complicated code execution are programmed using the foundational ideas of OOP languages.
- Programmers can develop code more rapidly and creatively thanks to polymorphism.
- Reuse is increased and coupling is decreased when software is coded legibly.
- Polymorphism allows the developer to reuse the program codes. It suggests that out-of-date classes and codes that have already been developed, checked, and put to use can be recycled as needed. It saves programmers time, which is helpful. As a result, these scripts and the classes that go along with them can be used with other methods.
- One variable can only hold one type of data, such as float, integer, long, double, and so on. Customers find it simpler to utilize and search for the various types of variables they use. Explore what a goto statement is in Python.
Suggested Article: Jump statement in Python
Head-to-Head Comparison of Compile-time and Run-time Polymorphism
Compile Time Polymorphism | Runtime Polymorphism |
The compiler handles call resolution in compile-time polymorphism. | The compiler will not resolve calls to runtime polymorphism. |
Also referred to as early binding, overloading, and static binding. | It is also known as overriding, late binding, or dynamic binding. |
A type of compile-time polymorphism known as “method overloading” involves combining many methods with the same name but different parameters, signatures, or return types. | A sort of runtime polymorphism known as “method overriding” occurs when a method with the same signature or set of parameters is associated with a different class. |
To do this, operator and function overloading are employed. | It is accomplished by using virtual functions and pointers. |
It enables speedy execution because the required method is known early in the compilation process. | It delivers slower execution than early binding because the method that needs to be executed is known at runtime. |
Build-time polymorphism is less versatile because everything is done at build-time. | Runtime polymorphism is more flexible because everything is performed at runtime. |
Advantages of Polymorphism
- It facilitates source code reprocessing for the coder. It means that previously written codes and classes can be reused, saving programmers’ time once they have been checked and run. As such, these codes and related classes might be used for several other methods.
- It is possible to store multiple data types, like integer, floating, double, long, etc., in a single variable. It makes finding and utilizing these kinds of user-used variables easier.
- Easier code debugging. Explore what the Python developer salary is for freshers.
- It helps maintain and decrease connectivity across various functionalities.
- allows programmers to write programs that use a single technique for multiple executions based on the circumstances.
- The ability for programming code to expand and utilize the prior program is one of its greatest advantages, as it saves developers time and labor.
- The core principle of object-oriented programming (OOP) languages is that this technique is also applied to large-scale code execution programming.
- Programmers can write codes more rapidly and creatively because of this polymorphism feature.
- The advantages of polymorphism assert that because it maximizes reusability and reduces coupling to produce understandable program code, it is inherently beneficial. While polymorphism occasionally results in a modest performance hit, it is not always required. It makes code maintenance easier and simplifies code reading in the future.
Explore the popular https://www.slainstitute.com/python-interview-questions-and-answers
Conclusion
One of the main ideas of OOP languages, polymorphism, explains the idea of using many classes with the same interface. These classes can all provide a different implementation of the interface. Explore all courses available at SLA Institute and enroll in any programming language for a better career in the software development field.