Method Overloading in Java

Method Overloading is a feature in Java that allows a class to have more than one method with the same name but different parameters (different type, number, or both). This enables methods to be called in different ways, providing flexibility and clarity in code.

Key Points on Method Overloading:

Syntax of Method Overloading:

Syntax Example

class ClassName {
    void methodName(type1 param1) {
        // code
    }
    
    void methodName(type1 param1, type2 param2) {
        // code
    }
    
    // Additional overloaded methods
}

Example of Method Overloading in Java:

This example demonstrates how method overloading works with different parameter types and counts.

Code Example: Method Overloading

class MathOperations {
    // Method to add two integers
    int add(int a, int b) {
        return a + b;
    }
    
    // Method to add three integers
    int add(int a, int b, int c) {
        return a + b + c;
    }
    
    // Method to add two double values
    double add(double a, double b) {
        return a + b;
    }

    // Method to add an array of integers
    int add(int[] numbers) {
        int sum = 0;
        for (int num : numbers) {
            sum += num;
        }
        return sum;
    }
}

public class TestOverloading {
    public static void main(String[] args) {
        MathOperations math = new MathOperations();
        
        System.out.println("Sum of two integers: " + math.add(5, 10)); // Calls the first add method
        System.out.println("Sum of three integers: " + math.add(5, 10, 15)); // Calls the second add method
        System.out.println("Sum of two doubles: " + math.add(5.5, 10.5)); // Calls the third add method
        System.out.println("Sum of an array of integers: " + math.add(new int[]{1, 2, 3, 4, 5})); // Calls the new overloaded method
    }
}

Output

Sum of two integers: 15
Sum of three integers: 30
Sum of two doubles: 16.0
Sum of an array of integers: 15

Detailed Explanation:

By leveraging method overloading, developers can create more intuitive and flexible interfaces, leading to cleaner and more maintainable code.