Overriding vs Overloading
What You'll Learn
You'll learn the key differences between method overriding and method overloading — two similar-sounding concepts that work in completely different ways.
The Core Distinction
Overriding and overloading are both ways to have multiple methods with the same name, but they serve different purposes:
-
Overriding happens in an inheritance relationship. A subclass provides a new implementation for a method that already exists in its superclass. The method signature (name + parameters) must be exactly the same.
-
Overloading happens within the same class. You create multiple methods with the same name but different parameter lists. No inheritance required.
Side-by-Side Comparison
Overriding
class Animal {
void makeSound() {
System.out.println("Generic sound");
}
}
class Dog extends Animal {
@Override
void makeSound() { // Same signature, different behavior
System.out.println("Bark!");
}
}
Overloading
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) { // Same name, different parameters
return a + b + c;
}
}
The Analogy
Think of overloading like having multiple phone numbers (work, mobile, home) — same person, different ways to reach them.
Think of overriding like a child correcting their parent's old advice — replacing the inherited behavior with updated behavior.
Quick Reference
| Feature | Overriding | Overloading |
|---|---|---|
| Requires inheritance? | Yes | No |
| Signature | Identical | Different parameters |
| Return type | Must be compatible | Can differ |
| Purpose | Change inherited behavior | Provide alternatives |
Key Takeaway: Overriding replaces a superclass method with the same signature; overloading creates multiple methods with the same name but different parameters in the same class.