Polymorphism in Java: Definition, Types, and Real-Life Examples
Polymorphism means "many forms." In Java, it's the ability of an object, method, or reference to behave differently depending on the context in which it's used.
Types of Polymorphism
1. Compile-Time Polymorphism (Method Overloading)
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
}
2. Runtime Polymorphism (Method Overriding)
class Animal {
void sound() { System.out.println("Animal sound"); }
}
class Cat extends Animal {
@Override
void sound() { System.out.println("Cat meows"); }
}
Animal a = new Cat();
a.sound(); // Output: Cat meows
Real-Life Examples
- A person can act as a student in college, an employee at work, and a customer at a store — the same person, different roles
- A single "pay()" method can process credit card, UPI, or wallet payments differently depending on the object calling it
- A "draw()" method behaves differently for a Circle, Square, or Triangle object, even though it's called the same way
Why Polymorphism Matters
- Lets you write flexible code that works with objects of different types through a common interface
- Reduces the need for long if-else or switch chains based on object type
- Makes it easy to extend a system with new classes without changing existing code
Runtime polymorphism in Java is achieved through dynamic method dispatch, where the JVM decides which overridden method to call based on the actual object type at runtime.
Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.