🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

Method Overloading

Java 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 multiple add 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:

  1. Same method name: Overloaded methods must have the same name.
  2. Different parameter lists: Overloaded methods must have different parameter lists, which can include a different number of parameters, different types of parameters, or both.
  3. 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.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.