Method Overloading means defining multiple methods in the same class with the same name but different parameters (type, number or order).
Example
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;
}
}
Ways to overload
- Different number of arguments:
add(int, int)
vsadd(int, int, int)
- Different types of arguments:
add(int, int)
vsadd(double, double)
- Different order:
print(String, int)
vsprint(int, String)
Features
- Happens at compile-time β Also called compile-time polymorphism.
- Improves readability and flexibility.
- Works only in the same class (or inherited class).
- Can overload:
- instance methods,
- constructors,
- static methods.
Comparison
Overloading vs Overriding
Feature | Overloading | Overriding |
---|---|---|
Occurs In | Same class | Subclass (inheritance) |
Params | Must be different | Must be same |
Return Type | Can differ | Must be same (or covariant) |
Polymorphism Type | Compile-time | Runtime |
Tip
If methods have the same name but different parameters, itβs overloading.
Changing only the return type wonβt work - the compiler will complain.
Parent: _OOP Concepts