What is polymorphism?
Interview preparation resource from Gate Smashers.
Polymorphism is an object-oriented programming concept in which code can use objects through a common interface or base type, while each concrete type provides its own behavior for the same operation. For example, code can call processPayment on a PaymentMethod without needing to know whether the actual object is a CreditCard, PayPal, or BankTransfer implementation.
Definition
The word polymorphism means “many forms.” In OOP, it allows different object types to respond to the same operation in type-specific ways. The calling code relies on a shared contract, such as an interface or base class, rather than on a particular concrete class.
How it works
A common interface or base class declares an operation, and concrete classes implement or override that operation. When code invokes the operation through the common type, the behavior associated with the actual object is used.
- Common contract: A type such as PaymentMethod defines processPayment.
- Concrete implementations: Classes such as CreditCard, PayPal, and BankTransfer provide their own payment behavior.
- Caller code: The caller works with PaymentMethod and can use any compatible implementation without changing its logic.
Example
A notification system can define a Notification interface with a sendNotification operation. Email, SMS, and Push implementations can each deliver the message through their respective channel. The caller invokes the same operation regardless of the notification type.
Benefits
Polymorphism reduces coupling between client code and concrete classes. It makes systems easier to extend because a new implementation can often be added by following the existing interface, without modifying code that already depends on that interface.
