Method Overloading
Method overloading in Java allows a class to have multiple methods with the same name but different parameter lists. The methods are distinguished by the number, types, or order of their parameters. This provides flexibility and enhances code readability. Here's an example of method overloading:
public class MathOperations {
// Method to add two integers
public int add(int a, int b) {
return a + b;
}
// Method to add three integers
public int add(int a, int b, int c) {
return a + b + c;
}
// Method to add two doubles
public double add(double a, double b) {
return a + b;
}
// Method to concatenate two strings
public String add(String a, String b) {
return a + b;
}
public static void main(String[] args) {
MathOperations math = new MathOperations();
// Using the first add method
System.out.println("Sum of two integers: " + math.add(5, 7));
// Using the second add method
System.out.println("Sum of three integers: " + math.add(3, 6, 9));
// Using the third add method
System.out.println("Sum of two doubles: " + math.add(3.5, 2.5));
// Using the fourth add method
System.out.println("Concatenation of two strings: " + math.add("Hello", "World"));
}
}
In this example:
- The
MathOperations
class has multipleadd
methods with different parameter lists. - There are methods for adding integers, adding doubles, and concatenating strings.
- The methods are invoked based on the type and number of arguments provided during the method call.
Key points about method overloading:
- Same method name: Overloaded methods must have the same name.
- Different parameter lists: Overloaded methods must have different parameter lists, which can include a different number of parameters, different types of parameters, or both.
- Return type: The return type alone is not sufficient to distinguish overloaded methods.
Method overloading is a powerful feature that enhances the flexibility and readability of code. It allows developers to use a familiar method name for different variations of a task, making the code more intuitive and easier to understand.