2. What is method overloading?
If a class has multiple methods having same name but different
in parameters, it is known as Method Overloading.
Advantage of method overloading:
Increases the readability of the program..
3. Ways to overload
the method
There are two ways to overload the
method in java:
1.By changing number of arguments
2.By changing the data type
4. 1.Changing no. of arguments:
public class Sum {
public int sum(int x, int y)
{
return (x + y);
}
public int sum(int x, int y, int z)
{
return (x + y + z);
}
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(5, 5));
System.out.println(s.sum(5, 5, 10));
}
}
OUTPUT:
10
20
5. 2.Changing data type of arguments:
OUTPUT:
10
24.9
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(5,5));
System.out.println(Adder.add(12.3,12.6));
}}
6. In java, method overloading is not possible by changing
the return type of the method only because of ambiguity
Why Method Overloading is not possible by changing
the return type of method only?
7. Example:
class Adder{
static int add(int a,int b){return a+b
;}
static double add(int a,int b){return
a+b;}
}
class TestOverloading3{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
//ambiguity
}}
Output:
Compile Time Error: method
add(int,int) is already defined in
class Adder
8. Few Valid/invalid cases of method overloading
Case 1:
int mymethod(int a, int b, float c)
int mymethod(int var1, int var2, float var3)
Result: Compile time error. Argument lists are exactly same. Both methods are having same
number, data types and same sequence of data types.
Case 2:
int mymethod(int a, int b)
int mymethod(float var1, float var2)
Result: Perfectly fine. Valid case of overloading. Here data types of arguments are different.
9. Case 3:
int mymethod(int a, int b)
int mymethod(int num)
Result: Perfectly fine. Valid case of overloading. Here number of arguments are
different.
Case 4:
float mymethod(int a, float b)
float mymethod(float var1, int var2)
Result: Perfectly fine. Valid case of overloading. Sequence of the data types of parameters are
different, first method is having (int, float) and second is having (float, int).
Case 5:
int mymethod(int a, int b)
float mymethod(int var1, int var2)
Result: Compile time error. Argument lists are exactly same. Even though return type of
methods are different, it is not a valid case. Since return type of method doesn’t matter while
overloading a method.