Method Overloading (Compile-time Polymorphism)
Method Overloading happens when a class has multiple methods with the same name, but different parameters (different number of arguments or different types).
Breakdown of your Math example:
class MathOperations {
// Version 1: Adds two numbers
int add(int a, int b) {
return a + b;
}
// Version 2: Adds three numbers
int add(int a, int b, int c) {
return a + b + c;
}
}
Why use this? Instead of creating confusing names like addTwoNumbers() and addThreeNumbers(), we use one clean name: add(). Java is smart enough to know which one to call based on how many numbers you provide.
2. Method Overriding (Runtime Polymorphism)
Method Overriding happens when a Child class provides a specific implementation for a method that is already defined in its Parent class.
The method name and parameters must be exactly the same.
This allows a child to “change” the behavior inherited from the parent.
Example of Overriding:
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Cat extends Animal {
@Override // This tells Java we are replacing the parent's behavior
void makeSound() {
System.out.println("Meow Meow");
}
}
Why use this?
Every animal makes a sound, but they all make different sounds. Overriding allows the Cat to define its own specific sound while still being an Animal.
3. Comparison for University Exams
This is a very frequent question in university interviews and mid-terms.
| Feature | Method Overloading | Method Overriding |
| Type | Compile-time Polymorphism. | Runtime Polymorphism. |
| Class | Occurs within the same class. | Occurs between Parent and Child classes. |
| Parameters | Must be different. | Must be the same. |
| Inheritance | Not required. | Mandatory (needs extends). |
4. Real-life Example: A Smartphone
Think of the “Power Button” on your phone:
Case 1: Press it briefly -> Screen turns off (Method 1).
Case 2: Press and hold it -> Phone restarts (Method 2).
This is Overloading—the same button does different things based on how you “input” the press!