In this Java article we want to learn about Java Method Overloading, in Java method overloading is a feature that allows class to have multiple methods with the same name but with different parameters. it means that you can create several methods with the same name.
When Java see a method call, it examines the arguments passed to the method, and it determine which method should be called. Java uses different number and types of the arguments to identify appropriate method. if there are multiple methods with the same name, Java checks the parameters to determine which method to call.
This is an example of working with method overloading
1 2 3 4 5 6 7 8 9 |
public class MyClass { public int add(int x, int y) { return x + y; } public double add(double x, double y) { return x + y; } } |
In this example MyClass class has two methods with the same name add. but one method takes two int parameters, and the other one takes two double parameters. when you call add method with two int values, Java will call first add method. if you call add method with two double values, Java will call the second add method.
Benefits of Java Method Overloading
Java method overloading provides several benefits:
- Simplicity: Method overloading simplifies the code by reducing number of method names required.
- Readability: Overloaded methods make the code more readable, because it allows developers to use descriptive method names that accurately reflect the functionality of the method.
- Flexibility: Method overloading provides flexibility, because it allows developers to create methods that accept different types and numbers of arguments.
This is the complete code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class OverloadingExample { public static void main(String[] args) { int result1 = add(2, 3); double result2 = add(2.5, 3.5); System.out.println("Result 1: " + result1); System.out.println("Result 2: " + result2); } public static int add(int x, int y) { return x + y; } public static double add(double x, double y) { return x + y; } } |
In this example we have created a class called OverloadingExample that contains two add methods, one takes two int parameters and another one takes two double parameters. in the main method, we call add method twice, once with two int values and once with two double values.
Run the code this will be the result