What is Polymorphism?
Polymorphism means "many forms".
In Java, polymorphism allows a single action to behave differently based on the object that performs it.
👉 It enables one interface to be used for different underlying data types.
Types of Polymorphism in Java:
- Compile-time Polymorphism (Method Overloading)
- Runtime Polymorphism (Method Overriding)
1. Compile-time Polymorphism (Method Overloading)
Occurs when multiple methods have the same name but different parameters (number or type).
Example: Method Overloading
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(2, 3)); // 5
System.out.println(calc.add(2.5, 3.5)); // 6.0
System.out.println(calc.add(1, 2, 3)); // 6
}
}
2. Runtime Polymorphism (Method Overriding)
Occurs when a child class provides a specific implementation of a method that is already defined in the parent class.
Example: Method Overriding
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
@Override
void sound() {
System.out.println("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal a;
a = new Dog();
a.sound(); // Dog barks
a = new Cat();
a.sound(); // Cat meows
}
}
Real-life Analogy of Polymorphism:
- Method Name:
draw()
- Circle.draw() → draws a circle
- Rectangle.draw() → draws a rectangle
- Same method name → different behavior depending on the object type
Key Differences Between Overloading & Overriding:
| Feature |
Method Overloading |
Method Overriding |
| Type |
Compile-time polymorphism |
Runtime polymorphism |
| Class |
Same class |
Parent and child classes |
| Signature change |
Yes |
No (method name & signature same) |
| Inheritance required |
No |
Yes |
Summary
| Term |
Meaning |
| Polymorphism |
One method, many forms |
| Overloading |
Same method name, different parameters |
| Overriding |
Child class changes parent method |
@Override |
Annotation to ensure overriding is correct |