🦸 What is Polymorphism?
Polymorphism means “many forms.” It’s the ability of a single method, class, or object to take different forms or behave differently depending on the context.
🔗 Simple Definition
One interface, many implementations.
🌟 Why is Polymorphism Important?
It allows us to write flexible, reusable, and extensible code. Instead of writing separate methods for every single type, you write one general method, and each object handles its own behavior.
🔥 Types of Polymorphism in Java
1. Compile-time Polymorphism (Method Overloading)
This happens when you have multiple methods with the same name but different parameter lists (different number or types of arguments).
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) { // same name, different parameters
return a + b;
}
}
✅ Which add()
gets called depends on the parameters passed when calling it. This decision is made at compile time.
2. Runtime Polymorphism (Method Overriding)
This happens when a child class provides its own version of a method that already exists in the parent class. The method that gets called is decided at runtime based on the actual object type.
class Animal {
void makeSound() {
System.out.println("Some generic animal sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Woof Woof");
}
}
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Dog(); // Reference is Animal, actual object is Dog
myAnimal.makeSound(); // Woof Woof (Dog's version is called)
}
}
✅ Even though the reference type is Animal
, the actual object type (Dog) decides which makeSound()
gets called — this is runtime polymorphism.
🔗 Why is Polymorphism useful?
✅ Makes your code more flexible — you can work with parent references but actual behavior is decided by the real object (child class).
✅ Makes your code extensible — you can add new child classes without changing existing code.
🚀 Quick Analogy
Think of a universal remote control (parent class). It works for different TVs (child classes), but the actual behavior (what happens when you press “Power”) depends on the brand of the TV.