Method Overloading in Java

  • When you have more than one functions with the same name but with the different number of arguments, type of arguments, or the order of arguments, then such concept is called method overloading.
  • In method overloading, the return type of overloaded functions may be same or different.
  • It is an example of compile-time polymorphism.
  • Overloaded functions can have different modifiers.
  • You can also overload methods inherited from the superclass.

Note- By changing the return type or access modifiers or both, you cannot achieve method overloading.

Method Overloading by changing the number of method parameters

class OverloadingExample
{
	int add(int number1, int number2)
	{
		return number1+number2;
	}
	int add(int number1, int number2, int number3)
	{
		return number1+number2+number3;
	}
}

Method Overloading by changing the type of method parameters

class OverloadingExample
{
	double add(int number1, int number2)
	{
		return number1+number2;
	}
	double add(double number1, int number2)
	{
		return number1+number2;
	}
}

Method Overloading by changing the order of method parameters

class OverloadingExample
{
	int add(int number1, double number2)
	{
		return number1+number2;
	}
	int add(double number1, int number2)
	{
		return number1+number2;
	}
}

Problem with Method Overloading

Implicit conversion happens when you pass an argument in a method call and data type of the corresponding parameter is not same. This may give compile time error when you call any one of the overloaded functions.

class Test
{
	public double add(int a, double b){
		return a+b;
	}
	public double add(double a, int b){
		return a+b;
	}
	public static void main(String args[]){
		Test t = new Test();
		t.add(1, 2);
	}
}

Output

error: reference to add is ambiguous

Note- To avoid such error, always go for an exact match of data type between arguments passed in a method call and parameter present in the method definition.