Skip to content

Method Overloading

Kaveesha Vishmini Kottahachchi edited this page May 13, 2024 · 1 revision
  • Method overloading is a feature in many programming languages, including Java, C++, and C#, that allows a class to have multiple methods with the same name but different parameters. The compiler determines which overloaded method to call based on the number, type, and order of the arguments provided. Method overloading is a form of compile-time polymorphism.

Here are the key points about method overloading:

  1. Same Method Name: In method overloading, you can define multiple methods within the same class with the same name.

  2. Different Parameters: The overloaded methods must have different parameter lists. This can include a different number of parameters, different types of parameters, or parameters in a different order.

  3. Return Type: The return type of the overloaded methods can be the same or different. However, the return type alone is not sufficient to overload a method; it's the method signature (method name and parameter list) that matters.

  4. Compile-Time Resolution: The appropriate overloaded method is determined by the compiler at compile time based on the arguments provided in the method call. Unlike method overriding, which is resolved at runtime, method overloading is resolved at compile time.

  5. Flexibility and Readability: Method overloading enhances code readability and provides flexibility by allowing multiple methods with similar functionality to have the same name. This can make the code more intuitive and easier to understand.

Here's a simple example in Java:

class MathOperations {
    // Method to add two integers
    static int add(int a, int b) {
        return a + b;
    }

    // Method to add three integers
    static int add(int a, int b, int c) {
        return a + b + c;
    }

    // Method to add two doubles
    static double add(double a, double b) {
        return a + b;
    }
}

public class Main {
    public static void main(String[] args) {
        int sum1 = MathOperations.add(2, 3);
        int sum2 = MathOperations.add(2, 3, 4);
        double sum3 = MathOperations.add(2.5, 3.5);

        System.out.println("Sum of integers: " + sum1);
        System.out.println("Sum of three integers: " + sum2);
        System.out.println("Sum of doubles: " + sum3);
    }
}
  • In this example, the MathOperations class has three overloaded add() methods with different parameter lists. The appropriate method is determined by the compiler based on the arguments provided in each method call. This is compile-time polymorphism achieved through method overloading.

Back