Method overloading is a feature in Java that allows multiple methods within the same class to have the same name but different parameter lists. The methods must differ in the number of parameters, parameter types, or the order of parameters. It is a form of compile-time polymorphism because the method to execute is determined by the compiler.
Key Points: • Multiple methods can share the same name if their parameter lists are different. • Overloading improves code readability by using a common method name for related operations. • Method overloading is resolved at compile time. • Changing only the return type is not sufficient for method overloading. • It is commonly used in constructors and utility methods.
Example: A Calculator class may have multiple add() methods to handle different types and numbers of inputs.
Code Example:
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
double add(double a, double b) {
return a + b;
}
}
public class Demo {
public static void main(String[] args) {
Calculator calculator = new Calculator();
System.out.println(calculator.add(10, 20));
System.out.println(calculator.add(10, 20, 30));
System.out.println(calculator.add(10.5, 20.5));
}
}Output:
30
60
31.0Valid Ways to Overload a Method:
• Different number of parameters
calculate(int a)
calculate(int a, int b)• Different parameter types
calculate(int a)
calculate(double a)• Different parameter order
calculate(int a, String b)
calculate(String b, int a)Invalid Overloading:
int calculate(int a)
double calculate(int a)
The above is invalid because only the return type differs.
Benefits of Method Overloading:
• Improves code readability • Reduces the need for multiple method names • Makes APIs easier to use • Supports compile-time polymorphism
Interview Tip: A concise interview answer is:
"Method overloading is the ability to define multiple methods with the same name in the same class but with different parameter lists. It is a form of compile-time polymorphism and helps improve code readability and flexibility."