Method Overloading in Java

if a class have multiple methods by same name but different parameters, it is known as Method Overloading.

Why method Overloading

Suppose we have to perform addition of given number but there can be any number of arguments, if we write method such as a(int, int)for two arguments, b(int, int, int) for three arguments then it is very difficult for you and other programmer to understand purpose or behaviors of method they can not identify purpose of method. So we use method overloading to easily figure out the program. For example above two methods we can write sum(int, int) and sum(int, int, int) using method overloading concept.

Advantage of method overloading

Method overloading increases the readability of the program.

Syntax:

 class class_Name
{
Returntype  method()
{
...... 
}
Returntype  method(datatype1 variable1)
{
...........
...........
}
Returntype  method(datatype1 variable1, datatype2 variable2)
{
..... 
.....  
}
Returntype  method(datatype2 variable2)
{
...........
...........
}
Returntype  method(datatype2 variable2, datatype1 variable1)
{
..... 
..... 
}
}

Different ways to overload the method

There are two ways to overload the method in java

  • By changing number of arguments or parameters
  • By changing the data type

By changing number of arguments

In this example, we have created two overloaded methods, first sum method performs addition of two numbers and second sum method performs addition of three numbers.

 class Addition
	{
	void sum(int a, int b)
	{
	System.out.println(a+b);
	}
	void sum(int a, int b, int c)
	{
	System.out.println(a+b+c);
	}
	public static void main(String args[])
	{
	Addition obj=new Addition();
	obj.sum(10, 20);
	obj.sum(10, 20, 30);
	}
 	}
Output :
30
60

method-overloading-in-java

In this example, we have created two overloaded methods that differs in data type. The first sum method receives two integer arguments and second sum method receives two float arguments.


 class Addition
 	{
 	void sum(int a, int b)
 	{
 	System.out.println(a+b);
 	}
 	void sum(float a, float b)
 	{
 	System.out.println(a+b);
 	}
 	public static void main(Stringargs[])
 	{
 	Addition obj=new Addition();
  	obj.sum(10, 20);
 	obj.sum(10.05, 15.20);
 	}
 	}
Output :
30
25.25