Method overloading
18 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Method overloading means two or more methods in one class have the same name but different parameters. Java picks the right one by looking at the arguments.
Same name, different parameters
Adding two numbers and adding three is the same job, so names like add2 and add3 feel clumsy. Method overloading lets several methods in a class share one name, as long as their parameter lists differ.
Example 1 · Two or three numbers, one name
public class AddOverload { public static void main(String[] args) { System.out.println(add(10, 20)); System.out.println(add(10, 20, 30)); }
static int add(int a, int b) { return a + b; }
static int add(int a, int b, int c) { return a + b + c; }}30 60
What this code does
- Two arguments match
add(int a, int b); three arguments matchadd(int a, int b, int c). - Each version is a full method with its own body. They share only the name.
The lists may differ in the number of parameters, their types, or the order of their types. You have used overloading all along: println has one version for int, one for double, one for String and more.
How Java picks a version
total(20, 10) and total(20.5, 10.25) call methods with the same name. Java picks the version whose parameters match the arguments, while compiling, before the program runs.
Example 2 · The int version or the double version
public class TypeOverload { public static void main(String[] args) { System.out.println(total(20, 10)); System.out.println(total(20.5, 10.25)); System.out.println(total(20, 10.5)); }
static int total(int a, int b) { System.out.print("int version: "); return a + b; }
static double total(double a, double b) { System.out.print("double version: "); return a + b; }}int version: 30 double version: 30.75 double version: 30.5
What this code does
total(20, 10): twointvalues match theintversion exactly.total(20.5, 10.25): twodoublevalues match thedoubleversion.total(20, 10.5): no version takes anintand adouble, so Java widens 20 to 20.0, as in Type conversion and casting (opens in a new tab), and uses thedoubleversion.
What does not count
You add double square(int n) next to int square(int n), and Java refuses. Only the parameter list counts: a different return type or different parameter names is not enough.
static int square(int n) { return n * n; }static double square(int n) { return n * n; } // error: method square(int) is already definedClassify
Valid overload or error?
Tap a pair of methods in one class, then tap what Java says.
Next step
Check your understanding
8 quick questions