Method overloading is a feature in Java that allows multiple methods within the same class to have the same name but different parameter lists. It improves code readability and is an example of compile-time polymorphism.
Key Points: • Overloaded methods must have different parameter lists in terms of number, type, or order of parameters. • Method overloading enables the same operation to be performed with different inputs. • The return type alone cannot be used to overload a method. • The compiler determines which overloaded method to invoke at compile time. • It improves code maintainability by using a common method name for related operations.
Example: A calculator class can have multiple add() methods to handle different numbers and types of arguments while keeping the method name consistent.
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;
}
}Interview Tip: A concise interview answer is:
"Method overloading is the ability to define multiple methods with the same name in the same class, provided their parameter lists are different. It is a form of compile-time polymorphism in Java."