Polymorphism in Programming
Definition and Different Examples
What is Polymorphism?
• Polymorphism means 'many forms'.
• It allows objects of different types to be treated as instances of the same
class.
• Supports code reusability and flexibility.
• Two main types: Compile-time and Run-time polymorphism.
Compile-Time Polymorphism
• Also known as Static Polymorphism.
• Achieved using method overloading or operator overloading.
• Decided at compile time.
Example: Method Overloading
(Java)
• class Calculator {
• int add(int a, int b) {...}
• double add(double a, double b) {...}
• int add(int a, int b, int c) {...}
• }
Example: Operator Overloading (C+
+)
• class Complex {
• Complex operator + (const Complex& other) {
• return Complex(real + [Link], imag + [Link]);
• }
• }
Run-Time Polymorphism
• Also known as Dynamic Polymorphism.
• Achieved through method overriding.
• Resolved at runtime using dynamic dispatch.
Example: Method Overriding (Java)
• class Animal { void sound() {...} }
• class Dog extends Animal { void sound() {...} }
• class Cat extends Animal { void sound() {...} }
Polymorphism with Interfaces
• Uses common interfaces implemented by different classes.
• Allows treating all objects through the interface reference.
Polymorphism in Python (Duck
Typing)
• class Dog: def speak(self): return 'Woof!'
• class Cat: def speak(self): return 'Meow!'
• def make_animal_speak(animal): print([Link]())
Summary of Polymorphism Types
• Compile-Time: Method Overloading, Operator Overloading (Java, C++)
• Run-Time: Method Overriding (Java, Python)
• Interface-Based: Java, C#
• Duck Typing: Python, Ruby
• Ad-hoc: Haskell, Rust, Scala