Method Overloading
Method overloading means defining multiple methods with the same name in the same class, but with different parameter lists (different number or types of parameters). Java decides which version to run based on the arguments you pass.
1. What is Method Overloading?
Method overloading means defining multiple methods with the same name in the same class, but with different parameter lists (different number or types of parameters). Java decides which version to run based on the arguments you pass.
2. Why is it used?
It lets you use one intuitive method name for similar operations that differ only in input type or count — like an add method that can work with two integers or three integers, without needing different method names for each case.
3. Real-Life Example
Think of a single word "cut" used for cutting paper, cutting vegetables, or cutting hair — same action name, but the specific tool and technique used depends on what's being cut. Method overloading works the same way, adapting based on what's passed in.
4. Syntax
javareturnType methodName(paramType1 a) { } returnType methodName(paramType1 a, paramType2 b) { }
5. Example Program
javaclass Calculator { int add(int a, int b) { return a + b; } int add(int a, int b, int c) { return a + b + c; } } public class OverloadingDemo { public static void main(String[] args) { Calculator calc = new Calculator(); System.out.println(calc.add(2, 3)); System.out.println(calc.add(2, 3, 4)); } }
Output:
5
96. Key Points to Remember
- Overloading is resolved at compile-time, based on the number and types of arguments.
- Changing only the return type (without changing parameters) is not enough to overload a method.
- Overloading is also called "compile-time polymorphism" or "static polymorphism."