Unit 4 · The Four Pillars in Depth · 11 min
Polymorphism: overloading and overriding
Polymorphism means 'many forms': the same method name behaves differently depending on the arguments (overloading) or on the object (overriding).
Why this matters
It is what makes code flexible. You can write one loop that calls draw() and every shape draws itself correctly.
Real-life analogy
The word 'run' means different things for a person, an engine and a program. Same name, different behaviour based on context.
Example
Java
class Calculator {
int add(int a, int b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
double add(double a, double b) { return a + b; }
}
class Animal {
void sound() { System.out.println("Some sound"); }
}
class Dog extends Animal {
@Override
void sound() { System.out.println("Woof"); }
}
class Cat extends Animal {
@Override
void sound() { System.out.println("Meow"); }
}
public class Main {
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println(c.add(2, 3));
System.out.println(c.add(2, 3, 4));
System.out.println(c.add(2.5, 3.5));
Animal[] animals = { new Dog(), new Cat(), new Animal() };
for (Animal a : animals) {
a.sound(); // decided at runtime
}
}
}Output
5 9 6.0 Woof Meow Some sound
Step by step
- 1The three add() methods share a name but differ in parameters — compile-time polymorphism (overloading).
- 2Dog and Cat override sound() with their own version — runtime polymorphism.
- 3`Animal a = new Dog();` is upcasting: the reference type is Animal, the object is a Dog.
- 4At runtime the JVM calls the Dog version. This is dynamic method dispatch.
Key points
- Overloading: same name, different parameter list, same class, resolved at compile time
- Overriding: same signature, parent and child, resolved at runtime
- @Override helps the compiler catch mistakes
- Return type alone cannot overload a method
Common mistakes
- Thinking two methods differing only by return type are overloaded
- Changing the parameter list while intending to override (it becomes overloading)
- Trying to override a private or static method
Try it yourself
- Overload an area() method for square, rectangle and circle.
- Create Shape, Circle and Square and call draw() through a Shape reference.