In high-level languages such as Python and Java, OOP or Object-oriented programming refers to software design organization around data and objects rather than logic and functions. An object is defined as a data field with unique attributes and behavior. In other words, OOP focuses on objects rather than logic. Such a programming model is ideal for large and complex programs requiring active updates and maintenance. Plus, it brings to the table the added benefits of scalability, efficiency, and code reusability.
OOP has four fundamental building blocks – polymorphism, encapsulation, abstraction, and inheritance. Since the scope of our article is limited to polymorphism in OOPs, we will discuss polymorphism in detail, including examples of polymorphism in Java and polymorphism in Python.
Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.
Polymorphism Definition
The simplest polymorphism definition would be that polymorphism means to exist in various forms. It has its roots in two Greek terms – ‘poly,’ meaning ‘numerous’ and ‘morph,’ which translates to ‘forms.’
To understand the concept better, let’s take a simple example first. Take the instance of cursor behavior, the very same cursor that you see moving around on the screen every time you use a mouse or trackpad. Depending on the user’s actions or the program mode, the cursor can take different forms, such as an arrow, a cross, a line, or an index finger.
Polymorphism is one of the most significant features of OOP. In Java and Python, variables, objects, and functions can exist in many forms. In polymorphism, a subclass or method defines its attributes and behaviors while retaining some of the functionalities of its parent class. That brings us to the inheritance, which allows you to create class hierarchies where a base class gives its attributes and behavior to a derived class. Subsequently, the functionalities of the derived class can be freely modified or extended as required. To this end, polymorphism ensures that the correct method is executed based on the type of the calling object.
To put it in perspective, suppose you have a class that displays the date and time. Now, you create a method that inherits the class and displays the message “Hello!” along with the date and time.
Example of Polymorphism in Java
Consider the superclass “Shapes” that has a method “area()”. Subclasses under “Shape” can be “Rectangle,” “Circle,” “Triangle,” etc., and each subclass has its method for calculating area. Applying the concepts of inheritance and polymorphism, the subclasses use the “area()” method to find the formula for calculating the area of the respective shape.
class Shapes {
public void area() {
System.out.println(“The formula for area of “);
}
}
class Triangle extends Shapes {
public void area() {
System.out.println(“Triangle is ½ * base * height “);
}
}
class Circle extends Shapes {
public void area() {
System.out.println(“Circle is 3.14 * radius * radius “);
}
}
class Main {
public static void main(String[] args) {
Shapes myShape = new Shapes(); // Create a Shapes object
Shapes myTriangle = new Triangle(); // Create a Triangle object
Shapes myCircle = new Circle(); // Create a Circle object
myShape.area();
myTriangle.area();
myShape.area();
myCircle.area();
}
}
The output of the above program code will be as follows:
The formula for the area of Triangle is ½ * base * height
The formula for the area of the Circle is 3.14 * radius * radius
Types of Polymorphism in OOPs
Polymorphism in OOPs is of two types – static (compile-time polymorphism) and dynamic (runtime polymorphism).
1. Static polymorphism
In Java, method overloading is the most common type of static polymorphism. It can create several methods of the same name within the same class but with different parameters. The parameter sets must differ in at least one of the following three criteria:
- The methods need to have different numbers of parameters.
- The parameter types need to be different. For example, if one method accepts a Long, the other accepts a String.
- The methods should accept the parameters in different orders. For example, if method 1 accepts a Long and a String, method two must accept a String and then a Long.
In method overloading, while calling the method, the compiler chooses which method to call based on the parameters passed while calling. This takes place at compile-time, and hence, this type of polymorphism is also referred to as compile-time polymorphism.
Following is a Java code example to show compile-time polymorphism. In this example, the method adds () is overloaded with two different types of parameters.
package staticPolymorphism;
public class Addition
{
void sum(int x, int y)
{
int c = x+y;
System.out.println(“ Addition of two numbers :” +c); }
void sum(int x, int y, int z)
{
int c = x+y+z;
System.out.println(“ Addition of three numbers :” +c); }
public static void main(String[] args)
{
Addition obj = new Addition();
obj.sum ( 45,34);
obj.sum(60, 32, 11);
}
}
The output of the above program will be:
Addition of two numbers:79
Addition of three numbers:103
2. Dynamic polymorphism
Dynamic or runtime polymorphism is achieved through method overriding. Here, methods are in different forms in different classes (method overriding), and instead of compile-time, the call to an overridden method is resolved at runtime. Now, upon assigning an object to a class reference and calling a method, the method in the object’s class gets executed. Since the object is created at runtime, the form of the method (in the object) which should be executed is only decided at runtime.
Following is a Java code example to show runtime polymorphism. In the example, there is a superclass “Animal” and three subclasses, “kangaroo,” “tiger,” and “fish.” Subclasses extend the superclass and override its “move()” method. The “move()” method is called by the reference variable of the parent class “Animal.”
class Animal{
void move(){
System.out.println(“Animals Move”);
}
}
class kangaroo extends Animal{
void move(){
System.out.println(“Kangaroos jump”);
}
}
class tiger extends Animal{
void move(){
System.out.println(“Tigers walk”);
}
}
class fish extends Animal{
void move(){
System.out.println(“Fish swim”);
}
}
class main{
public static void main(String args[]){
Animal A = new Animal();
Animal k = new kangaroo(); //upcasting
Animal t = new tiger(); //upcasting
Animal f = new fish(); //upcasting
A.move();
k.move();
t.move();
f.move();
}
}
The output of the above program will be:
Animals move
Kangaroos jump
Tigers walk
Fish swim
Polymorphism in Python
Polymorphism in Python is of three types – operator polymorphism, function polymorphism, and class polymorphism. Python also allows method overriding but not method overloading.
1. Operator polymorphism
In Python, the ‘+’ operator has dual usage. It is used for arithmetic addition operations in the case of integer data types, and for strings, the ‘+’ operator performs concatenations.
Following is a Python code example where the ‘+’ operator performs addition on integer data types:
num1 = 4
num2 = 5
print(num1+num2)
The output of the above program code is ‘9.’
Following is a Python code example where the ‘+’ operator performs concatenation on string data types:
str1 = “Good”
str2 = “Evening”
print(str1+” “+str2)
The output of the above program will be ‘Good Evening.’
2. Function polymorphism
The ‘len()’ function in Python is compatible with different data types such as list, string, tuple, dictionary, and set but returns specific information for each data type. Here’s an example:
print(len(“Programer”))
print(len([“Python”, “Java”, “C”]))
print(len({“Name”: “Kathy”, “Address”: “Texas”}))
The above program will have the following output:
9
3
2
3. Class Polymorphism
Extending the concept of polymorphism, Python allows multiple classes to have methods with the same name. Given below is an example to show polymorphism in class methods in Python. In the example, there are two classes, ‘Cat,’ and ‘Dog.’ They have a similar structure and have the same method names’ make_sound(),’ and ‘info().’
class Cat:
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
print(f”I am a cat. My name is {self.name}. I am {self.age} years old.”)
def make_sound(self):
print(“Meow”)
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
print(f”I am a dog. My name is {self.name}. I am {self.age} years old.”)
def make_sound(self):
print(“Bark”)
cat1 = Cat(“Minnie”, 3)
dog1 = Dog(“Tom”, 6)
for animal in (cat1, dog1):
animal.make_sound()
animal.info()
animal.make_sound()
The output will be as follows:
Meow
I am a cat. My name is Minnie. I am 3 years old.
Meow
Bark
I am a dog. My name is Tom. I am 6 years old.
Bark
4. Method Overriding
Python also allows child classes to inherit attributes and methods from the parent class. Certain methods and attributes can be redefined to fit the child class (method overriding). Polymorphism then allows access to the overridden methods and attributes with the same name as the parent class.
Following is a Python code example to illustrate method overriding:
from math import pi
class Shape:
def __init__(self, name):
self.name = name
def area(self):
pass
def fact(self):
return “I am a closed figure.”
def __str__(self):
return self.name
class Square(Shape):
def __init__(self, length):
super().__init__(“Square”)
self.length = length
def area(self):
return self.length**2
def fact(self):
return “Each angle in a square is equal to 90 degrees.”
class Circle(Shape):
def __init__(self, radius):
super().__init__(“Circle”)
self.radius = radius
def area(self):
return pi*self.radius**2
a = Square(4)
b = Circle(7)
print(b)
print(b.fact())
print(a.fact())
print(b.area())
The above program will have the following output:
Circle
I am a closed figure.
Each angle in a square is equal to 90 degrees.
153.93804002589985
Learn more about method overriding.
Advantages of Polymorphism in OOPs
Polymorphism in OOPs has three significant advantages. They are as follows:
- Polymorphism allows the reusability of code. Hence, once the classes are written, tested, and implemented, you can reuse them again and again. Plus, the code can be altered without affecting the original code. All of it saves significant time for the coder.
- In polymorphism, multiple data values can be stored in a single variable. Moreover, a variable’s value inherited from a superclass into a subclass can be modified without changing the variable’s value in the superclass or any subclass.
- Finally, polymorphism works with fewer lines of code, which, in turn, makes debugging easier for the programmer.
Way Forward
upGrad, in partnership with the prestigious Liverpool John Moores University, offers a rigorous online Master of Science in Data Science program for working professionals aspiring to make a career in data science. The course ends with a Master’s degree from LJMU and an Executive PG Program certification from IIIT Bangalore.
Program Highlights:
- 500+ hours of content, 60+ case studies and projects, 20+ live sessions
- Comprehensive coverage of 14+ tools and software such as Python, AWS, MySQL, and more
- Coaching sessions with industry experts
- Peer-learning and industry-networking
- 360-degree career assistance
One of the best higher EdTech platforms today, upGrad continues to inspire and prepare learners through a combination of cutting-edge technology, the latest pedagogy, industry partnerships, and a world-class faculty.
Learn data science courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.
Why is polymorphism used in OOPs?
In OOPs, polymorphism is the method that performs different tasks based on the object’s class that calls it. Thus, a message is sent to objects of multiple classes, and every object responds according to the properties of the class.
What is method overloading in Java?
In Java, two or more methods having the same name may differ in their parameters (different types of parameters, different numbers of parameters, or both). Such methods are called overloaded methods, and the feature is called method overloading.
What is the difference between overloading and overriding?
When two or more methods in the same class have different parameters but the same name, it is called overloading. On the other hand, overriding is when the superclass and the child class have the same method signature (name and parameters).
