Method Overloading in Java
beginner· OOP · Polymorphism
Problem
Method overloading lets a class declare several methods that share one name but differ in their parameter lists, with Java picking the matching version based on the arguments passed at compile time.
Define a pay-calculating method with three different parameter lists, and call each version.
Input
calculatePay(40); calculatePay(40, 200.0); calculatePay(5000.0, 500.0, 0.1)
Output
Pay (hours only): 800.0
Pay (hours + bonus): 1000.0
Pay (salary + bonus + tax): 4950.0
Java Program
Java
public class PayCalculator {
double calculatePay(int hours) {
return hours * 20.0;
}
double calculatePay(int hours, double bonus) {
return hours * 20.0 + bonus;
}
double calculatePay(double baseSalary, double bonus, double taxRate) {
return (baseSalary + bonus) * (1 - taxRate);
}
public static void main(String[] args) {
PayCalculator calc = new PayCalculator();
System.out.println("Pay (hours only): " + calc.calculatePay(40));
System.out.println("Pay (hours + bonus): " + calc.calculatePay(40, 200.0));
System.out.println("Pay (salary + bonus + tax): " + calc.calculatePay(5000.0, 500.0, 0.1));
}
}Output
Pay (hours only): 800.0
Pay (hours + bonus): 1000.0
Pay (salary + bonus + tax): 4950.0
Core Logic
Giving three methods the same name but different parameter counts and types lets the compiler pick the right one purely from how each call is written.
How It Works
- 1
calculatePay(int hours)handles a plain hourly calculation. - 2
calculatePay(int hours, double bonus)adds a bonus on top of the hourly pay — same name, one more parameter. - 3
calculatePay(double baseSalary, double bonus, double taxRate)handles a completely different calculation shape, keyed off having three parameters instead of one or two. - 4Java resolves which overload to call by matching each call site's argument count and types against the available signatures, entirely at compile time.
calculatePay(40) matches the one-parameter version and returns 800.0; calculatePay(40, 200.0) matches the two-parameter version and returns 1000.0; the three-argument call matches the third version and returns 4950.0.💡
Key Point: This is compile-time polymorphism — which method body runs is decided by the call's argument list before the program ever executes, unlike method overriding, which resolves at runtime based on an object's actual class.
Key Concepts
method overloadingcompile-time polymorphismparameter list