🔁 Method Overloading (Compile-Time Polymorphism)
✨ What It Is:
Overloading occurs when multiple methods have the same name but different parameter lists. These methods can exist in the same class or in a subclass.
✅ Key Rules:
- Must have different number, type, or order of parameters.
- Can have different return types.
- Happens at compile time (the compiler decides which version to call based on the arguments).
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
public class Main {
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println(c.add(2, 3)); // Output: 5
System.out.println(c.add(2.5, 3.5)); // Output: 6.0
System.out.println(c.add(1, 2, 3)); // Output: 6
}
}
🔄 Method Overriding (Runtime Polymorphism)
✨ What It Is:
Overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.
✅ Key Rules:
- Method name, return type, and parameters must match exactly.
- Must occur across parent-child class relationship.
- Happens at runtime (which method gets called depends on the object’s actual type).
- Use
@Override
annotation to make it explicit. - Access modifier can’t be more restrictive than in the parent.
🔧 Example:
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.makeSound(); // Output: Dog barks
}
}
🧠 Comparison Table
Feature | Method Overloading | Method Overriding |
---|---|---|
Class Relationship | Happens in the same class | Requires inheritance (parent-child) |
Method Signature | Must be different (parameters) | Must be exactly same |
Return Type | Can vary | Must be same or covariant (subtype) |
Access Modifier | Any (private, public, etc.) | Cannot be more restrictive than superclass |
Static Methods | Can be overloaded | Cannot be overridden (can only be hidden) |
Polymorphism Type | Compile-time polymorphism | Runtime polymorphism |
Binding Time | Decided at compile time | Decided at runtime |
Annotation Use | Optional | Recommended to use @Override |