⬅ Previous Topic
Inheritance in Programming - OOPNext Topic ⮕
Constructors and Destructors in OOP⬅ Previous Topic
Inheritance in Programming - OOPNext Topic ⮕
Constructors and Destructors in OOPPolymorphism is one of the core principles of object-oriented programming. The word polymorphism means "many forms". In programming, it refers to the ability of different classes or objects to respond to the same method name or operator in different ways.
Polymorphism allows you to write more flexible, extensible, and maintainable code. Instead of writing multiple versions of a method or function for each object type, you can write a single interface and have multiple implementations.
Suppose we want a function that can add either two or three numbers. Instead of writing differently named functions, we use the same function name with different parameters.
class Calculator:
function add(a, b):
return a + b
function add(a, b, c):
return a + b + c
obj = Calculator()
print(obj.add(2, 3)) # Should call the two-parameter version
print(obj.add(1, 2, 3)) # Should call the three-parameter version
Output:
5 6
That’s where compile-time binding comes in. The compiler checks the number of arguments and calls the appropriate version of the function before the program runs.
Imagine we have a base class Shape
with a method area()
. Different shapes like Circle and Rectangle can override this method to calculate their specific area.
class Shape:
function area():
return 0
class Circle inherits Shape:
function area():
return 3.14 * radius * radius
class Rectangle inherits Shape:
function area():
return length * width
# Using polymorphism
function printArea(shapeObject):
print(shapeObject.area())
obj1 = Circle(radius=5)
obj2 = Rectangle(length=4, width=6)
printArea(obj1) # Circle's area
printArea(obj2) # Rectangle's area
Output:
78.5 24
circle.area()
or rectangle.area()
directly?Great question! The power of polymorphism lies in abstraction. You can write code that works on the Shape
interface without knowing the actual type of the object. This makes your code more reusable and easier to extend.
Consider a remote control (interface). It can control a TV, AC, or Music System (different classes). The same button (method) might perform different actions depending on the device—this is polymorphism in action.
You can store objects of different subclasses in a single collection and invoke methods on them polymorphically.
shapes = [Circle(radius=3), Rectangle(length=5, width=2), Circle(radius=1)]
for shape in shapes:
print(shape.area())
Output:
28.26 10 3.14
⬅ Previous Topic
Inheritance in Programming - OOPNext Topic ⮕
Constructors and Destructors in OOPYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.