The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists
Overloaded functions have the same name but different types of arguments or parameters assigned to them. They can be used to calculate mathematical or logical operations within the number of assigned variables in the method.
Function overloading works by calling different functions having the same name, but the different number of arguments passed to it. There are many coding examples that can be shown in order to identify the benefits and disadvantages of function overloading properly.
int myMethod(int x)
int myMethod(int x,int y)
float myMethod(float x)
float myMethod(float x, float y)
double myMethod(double x)
double myMethod(double x, double y)
public class Simple {
static int addMethod(int x, int y) {
return x + y;
}
static float addMethod(float x, float y) {
return x + y;
}
public static void main(String[] args) {
int myNum1 = addMethod(3, 5);
float myNum2 = addMethod(2.3f, 5.26f);
System.out.println("int: " + myNum1);
System.out.println("float: " + myNum2);
}
}
Output:
int: 8
double: 7.5600004
class Simple
{
void sum (int a, int b)
{
System.out.println("Sum is: "+(a+b)) ;
}
void sum (double a, double b)
{
System.out.println("Sum is: "+(a+b));
}
public static void main (String[] args)
{
Calculate cl = new Calculate();
cl.sum (2,5); //sum(int a, int b) is method is called.
cl.sum (2.6, 3.3); //sum(double a, double b) is called.
}
}
Output:
Sum is: 7
Sum is: 5.9
Function overloading works with the same name. So we do not have to create methods that have the same thing as work that is done inside a respective function. The functionality not only resolves the problem of conflicting naming but also improves the readability of the program.