What is Method Overloading?
We refer to these situations as “method overloading” when two or more methods share the same name but have different signatures. Each method is an overloaded method of the others, and they are overloaded methods of one another.
Method Signature
It includes the name of the method and a parameter list (number of parameters, type of the parameters, and order of the parameters). The return type and exceptions are not considered as part of it.
The example below uses Method Overloading:
public class MethodOverLoading { public static void main(String[] args) { addNumbers(3, 4); // Total Number of Parameter - X addNumbers(2.5, 6); //Data Type of parameter - X addNumbers(7, 1.9); //order of Parameter - pass }//main public static void addNumbers(int a, int b) { int r = a + b; System.out.println("Result of two num " + r); } public static void addNumbers(int a, double b) { double r = a + b; System.out.println("Result of two num " + r); } public static void addNumbers(double a, int b) { double r = a + b; System.out.println("Result of two num " + r); } }
Explanation:
- public class MethodOverLoading : This line defines a public class named MethodOverLoading.
- public static void main(String[] args) : This line defines the main method, which serves as the entry point of the program.
- addNumbers(3, 4);: This line calls the addNumbers method with two integer arguments: 3 and 4.
- addNumbers(2.5, 6);: This line calls the addNumbers method with a double argument:2.5 and an integer argument: 6
- addNumbers(7, 1.9);: This line calls the addNumbers method with an integer argument: 7 and a double argument: 1.9.
There are overloaded methods that match this combination, one with (int, int) and the other with (double, int) and another with ( int, double)
- public static void addNumbers(int a, int b) { … }: This method is an overloaded version of addNumbers that takes two integer parameters and calculates their sum.
- public static void addNumbers(int a, double b) { … }: This method is another overloaded version of addNumbers that takes an integer and a double parameter and calculates their sum.
- public static void addNumbers(double a, int b) { … }: This method is the third overloaded version of addNumbers that takes a double and an integer parameter and calculates their sum.
To summarize, the code demonstrates method overloading with three versions of the addNumbers method that deal with diverse parameter combinations. The method overloading is displayed based on the total number of parameters and data types of parameters.
Output:
Result of two num 7
Result of two num 8.5
Result of two num 8.9
Why method overloading?
Method overloading allows for the definition of multiple methods with the same name but different parameter lists. It enhances code readability by grouping similar operations under one method name. It provides flexibility because you can manage various types of data or number of parameters with the same method name. It promotes code reuse, reducing code duplication and making it easier to maintain.
Suppose you need to add given numbers, but the number of arguments can vary (e.g., either 2 or 3 arguments for simplicity).
To achieve this, you could create separate methods like sum2num(int, int) for two parameters and sum3num(int, int, int) for three parameters. However, this approach may cause confusion for other programmers and even yourself in the future since the methods have similar behavior but different names.
A better approach is to use method overloading. By overloading methods, you can create a single method named sum and define multiple versions for different parameter counts. Depending on the arguments provided, the appropriate version of the sum method will be called. This significantly improves the program’s readability and makes the code more understandable and maintainable.
How to perform method overloading in Java?
Method overloading can be done in different ways:
1) Method Overloading by changing number of parameters
In this example, we have created two methods, first add() method performs addition of two numbers and second add method performs addition of three numbers. To avoid creating instances of methods while invoking them, we are constructing static methods.
public class MethodOverLoading{ public static void main(String[] args) { addNumbers(3, 4); addNumbers(2, 6, 3); } public static void addNumbers(int a, int b) { int r = a + b; System.out.println("Result of two num " + r); } public static void addNumbers(int a, int b, int c) { int r = a + b + c; System.out.println("Result of three num " + r); } }
Explanation:
- public class MethodOverLoading : This line defines a public class named MethodOverLoading.
- public static void main(String[] args) : This line defines the main method, which serves as the entry point of the program. It takes a String array args as its parameter, allowing you to pass command-line arguments to the program.
- addNumbers(3, 4);: This line calls the addNumbers method with two integer arguments: 3 and 4.
- addNumbers(2, 6, 3);: This line calls the addNumbers method with three integer arguments: 2, 6, and 3.
- public static void addNumbers(int a, int b) { … }: This method is one of the overloaded versions of the addNumbers method. It takes two integer parameters and calculates their sum, which is stored in the variable r. Then, it prints the result using System.out.println().
- public static void addNumbers(int a, int b, int c) { … }: This method is another overloaded version of the addNumbers method. It takes three integer parameters a, b, and c, and calculates their sum, which is stored in the variable r. Then, it prints the result using System.out.println().
To summarize, the provided code demonstrates method overloading with two versions of the addNumbers method. The first version handles two integer parameters, and the second version handles three integer parameters. The appropriate version of the method is called based on the number of arguments passed when invoking the method.
Output:
Result of two num 7
Result of three num 11
2) Method Overloading by changing data type of parameters
Two distinct methods with different data types have been built in this example. Two integer parameters are given to the first add method, and two double arguments are given to the second add function.
public class MethodOverLoading{ public static void main(String[] args){ addNumbers(3, 4); addNumbers(2.6, 3.6); } public static void addNumbers(int a, int b) { int r = a + b; System.out.println("Result of two num " + r); } public static void addNumbers(double a, double b) { double r = a + b; System.out.println("Result of two num " + r); } }
Explanation:
- public class MethodOverLoading : This line defines a public class named MethodOverLoading.
- public static void main(String[] args) : This line defines the main method, which serves as the entry point of the program. It takes a String array args as its parameter, allowing you to pass command-line arguments to the program.
- addNumbers(3, 4);: This line calls the addNumbers method with two integer arguments: 3 and 4.
- addNumbers(2.6, 3.6);: This line calls the addNumbers method with two double arguments: 2.6 and 3.6.
- public static void addNumbers(int a, int b) { … }: This method is one of the overloaded versions of the addNumbers method. It takes two integer parameters and calculates their sum, which is stored in the variable r. Then, it prints the result using System.out.println().
- public static void addNumbers(double a, double b) { … }: This method is another overloaded version of the addNumbers method. It takes two double parameters and calculates their sum, which is stored in the variable r. Then, it prints the result using System.out.println().
To summarize, the provided code demonstrates method overloading with two versions of the addNumbers method. The first version handles two integer parameters, and the second version handles two double parameters. The appropriate version of the method is called based on the types of arguments passed when invoking the method.
Output:
Result of two num 7
Result of two num 6.2
3) Method Overloading by changing order of parameters
In this example, we can see that we can call the appropriate method based on the order of parameters provided when calculating the area of a rectangle or square.
public class RectangleAreaCalculator { public static void main(String[] args) { double area1 = RectangleAreaCalculator.calculateArea(4.5, 3.2); // Using width and height System.out.println("Rectangle area 1: " + area1); // Output: Rectangle area 1: 14.4 double area2 = RectangleAreaCalculator.calculateArea(5, 6); // Using height and width System.out.println("Rectangle area 2: " + area2); // Output: Rectangle area 2: 30.0 double area3 = RectangleAreaCalculator.calculateArea(5.5); // Using side length (square) System.out.println("Square area: " + area3); // Output: Square area: 30.25 } // Method to calculate the area of a rectangle using width and height public static double calculateArea(double width, double height) { return width * height; } // Method to calculate the area of a rectangle using height and width public static double calculateArea(int height, int width) { return height * width; } // Method to calculate the area of a square using side length public static double calculateArea(double sideLength) { return sideLength * sideLength; } }
In this example, we have three overloaded methods.
Explanation:
- public class RectangleAreaCalculator : This line defines a public class named RectangleAreaCalculator.
- public static void main(String[] args) : This line defines the main method, which serves as the entry point of the program. It takes a String array args as its parameter, allowing you to pass command-line arguments to the program.
- double area1 = RectangleAreaCalculator.calculateArea(4.5, 3.2);: This line calls the calculateArea static method of the RectangleAreaCalculator class, passing 4.5 as the width and 3.2 as the height. The method calculates the area of a rectangle using the provided width and height and returns the result, which is stored in the variable area1.
- System.out.println(“Rectangle area 1: ” + area1);: This line prints the value of area1, which represents the area of the rectangle with the width 4.5 and height 3.2
- double area2 = RectangleAreaCalculator.calculateArea(5, 6);: This line calls the calculateArea static method of the RectangleAreaCalculator class, passing 5 as the height and 6 as the width. The method calculates the area of a rectangle using the provided height and width and returns the result, which is stored in the variable area2.
- System.out.println(“Rectangle area 2: ” + area2);: This line prints the value of area2, which represents the area of the rectangle with the height 5 and width 6.
- double area3 = RectangleAreaCalculator.calculateArea(5.5);: This line calls the calculateArea static method of the RectangleAreaCalculator class, passing 5.5 as the side length. The method calculates the area of a square using the provided side length and returns the result, which is stored in the variable area3.
- System.out.println(“Square area: ” + area3);: This line prints the value of area3, which represents the area of the square with the side length 5.5.
- calculateArea(double width, double height): This method takes width and height as parameters and calculates the area of a rectangle.
- calculateArea(int height, int width): This method takes height and width as parameters and calculates the area of a rectangle. The order of parameters is different from the first method.
- calculateArea(double sideLength): This method takes a single parameter (side length) and calculates the area of a square, which is a special case of a rectangle.
The code calculates and prints the areas of two rectangles and one square using the RectangleAreaCalculator class, which contains static methods for area calculation. The static methods allow direct invocation on the class without creating an instance of the class.
Output:
Rectangle area 1: 14.4
Rectangle area 2: 30.0
Square area: 30.25