Polymorphism is an object-oriented programming (OOP) concept that allows objects of different classes to be treated as instances of the same class through a common interface. The term “polymorphism” comes from the Greek words “poly” (meaning many) and “morph” (meaning form), signifying the ability of one entity to take many forms. In programming, polymorphism allows for method overriding and method overloading, enabling more flexible and reusable code.
Definition: Polymorphism allows objects of different classes to be treated as objects of a common superclass. It is typically achieved through method overriding or overloading.
There are two main types of polymorphism:
- Compile-time polymorphism (also called static polymorphism): Achieved through method overloading or operator overloading, where the method to be invoked is determined at compile-time.
- Runtime polymorphism (also called dynamic polymorphism): Achieved through method overriding, where the method to be invoked is determined at runtime based on the objectโs actual type, often using inheritance and interfaces.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Dog barks")
Polymorphism is particularly useful in situations where you want to use a common interface but allow different objects to implement or override functionality in their own way. For example, a draw()
method in a Shape
class can be overridden by classes like Circle
, Square
, or Triangle
, each providing a specific implementation for drawing the shape.
Leave a Reply