🔄 What Is Polymorphism?
Polymorphism simply means “many forms.” In Java, it lets the same method or object behave in different ways depending on the situation.
💡 Think of it like this:
Imagine a single remote control that can operate a TV, a speaker, or an AC. It’s the same remote, but depending on which device it’s controlling, the function changes. That’s polymorphism in action.
There are two main types:
1. Compile-Time Polymorphism (Static Binding)
Achieved through method overloading—same method name, different parameter lists.
2. Runtime Polymorphism (Dynamic Binding)
Achieved through method overriding—a subclass provides a specific implementation of a method already defined in its superclass.
🧪 1. Compile-Time Polymorphism (Method Overloading)
class Printer {
void print(String msg) {
System.out.println("Message: " + msg);
}
void print(int number) {
System.out.println("Number: " + number);
}
}
// Usage
Printer p = new Printer();
p.print("Hello"); // Message: Hello
p.print(123); // Number: 123
Usage:
Printer p = new Printer(); p.print(“Hello”); // Message: Hello p.print(123); // Number: 123
The compiler decides which method to call based on the argument type.
🧪 2. Runtime Polymorphism (Method Overriding)
class Animal {
void makeSound() {
System.out.println(“Animal makes a sound”);
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println(“Dog barks”);
}
}
// Usage
Animal a = new Dog();
a.makeSound(); // Output: Dog barks
Usage:
Animal a = new Dog();
a.makeSound(); // Output: Dog barks
Even though the reference is of type Animal
, the actual method called is from Dog
—decided at runtime.
🧠 Why Use Polymorphism?
- Code Reusability: Write generic code that works with multiple types.
- Flexibility: Add new behaviors without changing existing code.
- Maintainability: Cleaner, more modular code.
🌍 Real-World Examples of Polymorphism
✅ 1. Payment Processing System
interface Payment { void pay(double amount); } class CreditCard implements Payment { public void pay(double amount) { System.out.println(“Paid ₹” + amount + ” using Credit Card”); } } class UPI implements Payment { public void pay(double amount) { System.out.println(“Paid ₹” + amount + ” using UPI”); } }
Usage:
Payment payment = new UPI(); payment.pay(500); // Output: Paid ₹500 using UPI
The same pay()
method behaves differently depending on the payment method.
✅ 2. Media Player
A MediaPlayer
class might have a method play()
:
AudioPlayer
plays MP3sVideoPlayer
plays MP4sStreamingPlayer
plays online content
All override the same play()
method, but the behavior changes based on the media type.
✅ 3. Human Roles
A person can be:
- A teacher in school
- A parent at home
- A customer in a store
Same person, different behaviors depending on the context—just like polymorphism!