What is Polymorphism?
Polymorphism is a big word that simply means “many forms.”
In Java, it means one action can behave differently depending on the object.
Real-Life Example: Remote Control
Imagine you have one remote control that can:
Control a TV
Control an AC
Control a projector
You’re pressing the same button, but it performs different actions based on the device.
That’s polymorphism in real life—same action, different behavior.
In Java: What does it mean?
In Java, polymorphism allows one method or one object to behave in multiple ways.
There are two types:
1. Compile-time Polymorphism (Method Overloading)
2. Runtime Polymorphism (Method Overriding)
1. Compile-time Polymorphism (Method Overloading)
Same method name, but different parameters.
Example: Calculator
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
}
add(2, 3) → returns 5
add(2.5, 3.1) → returns 5.6
add(1, 2, 3) → returns 6
Same method name (add), but it works differently depending on inputs.
2. Runtime Polymorphism (Method Overriding)
Same method, but defined differently in child classes.
Example: Animal Sounds
class Animal {
public void makeSound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println("Bark");
}
}
class Cat extends Animal {
public void makeSound() {
System.out.println("Meow");
}
}
public class Test {
public static void main(String[] args) {
Animal a;
a = new Dog();
a.makeSound(); // Output: Bark
a = new Cat();
a.makeSound(); // Output: Meow
}
}
Even though a is declared as Animal, the method behaves differently depending on the actual object (Dog or Cat).
Why is Polymorphism Useful?
1. Flexibility – Same code works in different ways.
2. Reusability – Code becomes reusable and cleaner.
3. Scalability – Easy to add new behaviors without changing existing code.
4. Maintainability – Easier to fix and manage.
Comments
Post a Comment