Developer Dictionary
Polymorphism
Definition
The provision of a single interface to entities of different types.
Deep Dive
Polymorphism, meaning "many forms," is a core concept in Object-Oriented Programming (OOP) that allows objects of different classes to be treated as objects of a common type. It provides a single interface to entities of different types, meaning that a common method call can behave differently depending on the specific object type on which it is invoked. This is often achieved through method overriding (where a subclass provides its own implementation of a method already defined in its parent class) or through interfaces (where classes adhere to a common contract of methods).
Examples & Use Cases
- 1A `draw()` method being called on a list of `Shape` objects (e.g., `Circle`, `Square`, `Triangle`), with each object implementing its own specific drawing logic
- 2Using a generic `Animal` reference to call the `makeSound()` method, which produces a "Woof!" for a `Dog` object and "Meow!" for a `Cat` object
- 3A `PaymentProcessor` interface that can process payments using different `CreditCard` types (Visa, MasterCard) through a unified `processPayment()` method.
Related Terms
InheritanceMethod OverridingInterface