Method Overloading
Overview
Method Overloading is a feature that allows a single Class to have multiple methods with the exact same name, provided they have different Parameter Lists (also known as Method Signatures).
This is a form of Compile-Time (Static) Polymorphism. It heavily improves code readability. Instead of forcing the developer to remember three different method names like printInt(), printString(), and printDouble(), you just name all of them print(). When you type print(5), the compiler looks at the integer argument and instantly knows which specific method version to link it to.
Syntax
public class MathUtils {
// Version 1: Adds two integers
public int add(int a, int b) {
return a + b;
}
// Version 2: Overloaded! Adds three integers (Different NUMBER of parameters)
public int add(int a, int b, int c) {
return a + b + c;
}
// Version 3: Overloaded! Adds two doubles (Different TYPE of parameters)
public double add(double a, double b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
MathUtils math = new MathUtils();
// The compiler perfectly resolves which method to trigger
System.out.println(math.add(5, 10)); // Calls Version 1
System.out.println(math.add(5.5, 2.0)); // Calls Version 3
}
}Common Pitfalls
- Changing ONLY the return type. If you have
public int compute(int x)and try to overload it by addingpublic double compute(int x), the compiler will crash! The parameter lists are identical, so the compiler has no idea which one you want when you callcompute(5). Return types do NOT play a role in overloading. - Ambiguous Method Calls. If you have
add(int, double)andadd(double, int), and you calladd(5, 5), the compiler will throw an error because both arguments are integers, and it cannot safely guess which method you want it to upcast the integers for.
Interview Questions
main() method in Java?Yes, you absolutely can! You can write public static void main(int[] args). However, when you execute the program, the JVM strictly searches for the exact signature public static void main(String[] args) to serve as the entry point. The others are just normal static methods.
Overloading occurs within the SAME class, requires DIFFERENT parameters, and is resolved at COMPILE time. Overriding occurs between Parent/Child classes, requires the EXACT SAME parameters, and is resolved dynamically at RUNTIME.
Real-World Example
The native System.out.println() command is the most famous example of Method Overloading in Java. The PrintStream class has over 10 overloaded versions of println to handle ints, doubles, chars, strings, and objects seamlessly.
// All of these use the same method name cleanly
System.out.println(100);
System.out.println("Hello");
System.out.println(true);Check Your Knowledge
Test your understanding of Method Overloading with these quick questions.