If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.
Advantage of Method Overloading: If we have to perform only one operation, having same name of the methods increases the readability of the program.
There are Two different ways to overload the method:
1. By Changing number of arguments
2. By changing the data type
Example of Method Overloading: By changing number of arguments
In this example, we have created two methods. First mul() performs multiplication of two numbers while second mul() performs multiplication of three numbers.
class Mul
{
static int mul(int a, int b)
{ return a*b;
}
static int mul(int a, int b, int c)
{ return a*b*c;
}
}
class Example
{
public static void main(String[] args)
{ System.out.println(Mul.mul(7,8));
System.out.println(Mul.mul (7,8,2));
}
}
OUTPUT:
56
112
Example of Method Overloading: By changing the data type
In this example, we have created two methods with same name using different data types. The first mul() method receives two integer arguments and second mul() method receives two double arguments.
class Mul
{
static int mul(int a, int b)
{ return a*b;
}
static double mul(double a, double b)
{ return a*b;
}
}
class Example1
{
public static void main(String[] args)
{ System.out.println(Mul.mul(7,8));
System.out.println(Mul.mul(7.6,8.3));
}
}
OUTPUT:
56
63.08
コメント