Polymorphism
📂 Phase 3: Object-Oriented Programming (Days 11–16) · JavaPolymorphism means "many forms" — the ability for the same method call to behave differently depending on the object it's actually operating on. Java achieves this through method overloading (compile-time) and method overriding (runtime).
Compile-Time Polymorphism: Method Overloading
Multiple methods share the same name but differ in parameters — Java decides which version to call based on the arguments, resolved at compile time.
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
Calculator calc = new Calculator();
System.out.println(calc.add(2, 3)); // 5 (int version)
System.out.println(calc.add(2.5, 3.5)); // 6.0 (double version)
Runtime Polymorphism: Method Overriding
A parent class reference can hold a child class object — the specific method that actually runs is determined at runtime based on the real object type, not the reference type.
class Animal {
void speak() {
System.out.println("Generic animal sound");
}
}
class Dog extends Animal {
@Override
void speak() {
System.out.println("Bark");
}
}
class Cat extends Animal {
@Override
void speak() {
System.out.println("Meow");
}
}
Animal a1 = new Dog();
Animal a2 = new Cat();
a1.speak(); // Bark — Dog's version runs, decided at runtime
a2.speak(); // Meow — Cat's version runs, decided at runtime
Why This Matters: Flexible, Extensible Code
Animal[] animals = { new Dog(), new Cat(), new Dog() };
for (Animal a : animals) {
a.speak(); // calls the correct overridden version for each object
}
// Bark
// Meow
// Bark
This is the foundation of writing flexible code — you can add new subclasses (like Cow, Bird) later without changing the loop above at all; each new subclass just needs its own speak() override.
Overloading vs Overriding
| Aspect | Overloading | Overriding |
|---|---|---|
| Resolved | Compile time | Runtime |
| Class | Same class | Parent and child class |
| Parameters | Must differ | Must be identical |
Interview tip: A frequently asked question is "Can you override a static method?" — No. Static methods are resolved at compile time based on reference type, so a static method in a subclass actually "hides" the parent's version rather than overriding it.