Defining Overloaded Methods
To define overloaded methods in Java, you need to follow these rules:
Method Name
The method name must be the same for all overloaded versions of the method.
Parameter List
The parameter list, which includes the number, types, and order of the parameters, must be different for each overloaded method. This is how the compiler determines which version of the method to call.
Here's an example of overloaded methods in a Java class:
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
}
In this example, the Calculator class has three add() methods:
add(int a, int b): Takes two int parameters and returns an int result.
add(double a, double b): Takes two double parameters and returns a double result.
add(int a, int b, int c): Takes three int parameters and returns an int result.
When you call the add() method on an instance of the Calculator class, the compiler will choose the appropriate implementation based on the arguments you pass.
Calculator calc = new Calculator();
int result1 = calc.add(2, 3); // Calls the add(int, int) method
double result2 = calc.add(2.5, 3.7); // Calls the add(double, double) method
int result3 = calc.add(1, 2, 3); // Calls the add(int, int, int) method
It's important to note that method overloading is based on the method signature, which includes the method name and the parameter list. Return types are not part of the method signature and cannot be used to distinguish between overloaded methods.