Method overloading in Java allows you to define multiple methods in the same class with the same name but with different parameter lists. This provides flexibility and improves code readability by allowing you to use the same method name for different behaviors based on the parameters passed. The methods must have different parameter types or a different number of parameters. Here's an overview of method overloading in Java:
public class Calculator { // 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; } }
The appropriate method is automatically chosen based on the number and type of arguments passed during the method call.
Calculator calculator = new Calculator(); int sum1 = calculator.add(5, 3); // Calls the first add method (int version) int sum2 = calculator.add(5, 3, 2); // Calls the second add method (int version) double sum3 = calculator.add(2.5, 3.7); // Calls the third add method (double version)