Method Overloading
Overview
Imagine you have a method that adds two integers. Later, you realize you also need to add two decimals. Instead of making two confusingly named methods (`addInts` and `addDecimals`), Java lets you use the same name for both!
Method Overloading means having multiple methods with the exact same name, as long as they take different inputs (parameters). Java is smart enough to look at what you pass in and pick the correct method.
1. Changing the Number of Parameters
You can have an `add(a, b)` and an `add(a, b, c)`. They share the name, but take different amounts of data.
2. Changing the Type of Parameters
You can have an `add(int a, int b)` and an `add(double a, double b)`. They share the name, but handle different types of data.
Syntax
One name, three different ways to use it.
public class MathHelper {
// 1. Two ints
public void add(int a, int b) {
System.out.println("Adding ints: " + (a + b));
}
// 2. Three ints
public void add(int a, int b, int c) {
System.out.println("Adding 3 ints: " + (a + b + c));
}
// 3. Two doubles
public void add(double a, double b) {
System.out.println("Adding decimals: " + (a + b));
}
}Common Pitfalls
- Trying to overload a method by ONLY changing what it returns (the return type). Java only looks at the inputs (parameters) to tell methods apart.
Interview Tips
- Overloading is known as 'Compile-Time Polymorphism' because the Java compiler figures out which method to run while translating your code.
Real-World Example
The classic `System.out.println()` is the ultimate example. It is overloaded to accept Strings, ints, doubles, booleans, and objects!
// We use overloaded methods every day without realizing it
System.out.println("Text");
System.out.println(100);
System.out.println(true);