Polymorphism in Java
What is Polymorphism?
Polymorphism means "many forms" — the ability of an object to take many forms.
In Java, it allows the same method name to perform different tasks, depending on:
- The type of parameters
- The object calling the method
Types of Polymorphism
Type | Description | Example |
---|---|---|
Compile-time Polymorphism | Method Overloading | Same method name, different parameters |
Runtime Polymorphism | Method Overriding | Same method name, same parameters, different class |
Method Overloading (Compile-Time)
Same method name, but different number/type/order of parameters in same class.
Example:
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 c = new Calculator();
System.out.println(c.add(2, 3)); // int version
System.out.println(c.add(2.5, 3.5)); // double version
System.out.println(c.add(1, 2, 3)); // 3 parameters
}
}
Output:
5
6.0
6
Overloading helps in code clarity and flexibility.
Method Overriding (Runtime)
Child class redefines a method of the parent class with same name and parameters.
Example:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog(); // Polymorphism in action
a.sound(); // Calls Dog's sound()
}
}
Output:
Dog barks
The method that runs is decided at runtime, depending on the object type.
Key Differences
Feature | Overloading | Overriding |
---|---|---|
Occurs in | Same class | Parent-child class |
Parameters | Must differ | Must be same |
Return type | Can differ | Should be same or covariant |
@Override used? | No | Yes |
Resolved at | Compile-time | Runtime |