Polymorphism
Many forms, one interface.
Polymorphism
Analogy: remote
Polymorphism is like a Universal Remote. You press the "Power" button.
- If you point it at the TV, it turns on the screen.
- If you point it at the AC, it starts the fan.
One button ("Power") does different things depending on the object.
The Shape Shifter
Imagine a game where you have a Shape.
- A Circle rolls.
- A Square slides.
- A Triangle spins.
But you just call performAction() on all of them!
Shape Shifter (Polymorphism)
Morph Into
Polymorphism Logic:
The performAction() method behaves differently depending on the current shape form.
Console Output
Waiting for action...The Code
Java Example
Switch language in Navbar
class Shape {
void performAction() {
System.out.println("Doing something...");
}
}
class Circle extends Shape {
void performAction() {
System.out.println("Rolling...");
}
}
class Square extends Shape {
void performAction() {
System.out.println("Sliding...");
}
}
This allows you to treat all shapes the same way:
Java Example
Switch language in Navbar
Shape s = new Circle();
s.performAction(); // Output: Rolling...
Advanced Concepts
Operator Overloading
Polymorphism isn't just for methods! In some languages (like C++ or Python), you can redefine how operators like + work.
- Numbers:
1 + 2 = 3(Addition) - Strings:
"Hello " + "World" = "Hello World"(Concatenation) - Custom Objects:
Vector(1, 2) + Vector(3, 4) = Vector(4, 6)(Vector Addition)
Java Example
Switch language in Navbar
// Java doesn't support Operator Overloading
// We use methods instead:
class Vector {
int x, y;
Vector(int x, int y) { this.x = x; this.y = y; }
Vector add(Vector other) {
return new Vector(x + other.x, y + other.y);
}
}
Vector v1 = new Vector(1, 2);
Vector v2 = new Vector(3, 4);
Vector v3 = v1.add(v2);
Up Next
Abstraction