Polymorphism
Polymorphism
An OOP concept where a single method can take multiple forms, allowing for the definition of different behaviour while sharing the same method name.
The term polymorphism comes from the Greek words "poly"(many) and "morph"(form), meaning many forms.
Types of Polymorphism
Static Polymorphism (Compile-Time)
- Achieved through method overloading.
- It allows multiple methods in the same class to have the same name but different parameter lists.
- The compiler determines which method to invoke based on the method signature.
public class Calculator {
public int add(int a, int b) { // method to add two integers
return a + b;
}
public double add(double a, double b) { // Overloaded method to add two doubles
return a + b;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(2, 3));
System.out.println(calc.add(2.5, 3.5));
}
}
- Polymorphism is not the same as inheritance.
- While inheritance enables polymorphism, they are distinct concepts.
Dynamic Polymorphism (Run-Time)
- Achieved through method overriding (inheritance).
- The method to be executed is determined at runtime based on the object's type.
class Bird {
public void fly() { System.out.println("This bird can fly."); }
}
class Penguin extends Bird {
@Override
public void fly() { System.out.println("Penguins cannot fly."); }
}
It is very important to distinguish method overloading and method overriding:
| Overloading | Overriding | |
|---|---|---|
| Definition | Same method name with different parameters in the same class | Subclass provides a new version of a method inherited from the parent class |
| Purpose | Provide multiple ways to perform a similar action | Must be the same as parent method. |
| Parameters | Must differ (number or type) | Must be the same as parent method |
| Return type | Can differ if parameters differ. | Must be the same (or compatible) as parent method |
| Requirements | Method should be in the same class or inherited | Requires inheritance |