by BehindJava

What is method overloading in Java

Home » java » What is method overloading in Java

In this tutorial, we are going learn method overloading in detail.

Method overloading can be achieved within a class having same method names but different parameters. Possibilities in method overloading

Having differences in the number of parameters or arguments we pass to a method.

Sample Code Snippet:

public class Overloading {
    public void overLoad(int x,int y)
	{
    	int i=x+y;
    	System.out.println(i);
	}
    public void overLoad(int x,int y,int z)
	{
    	int j=x+y+z;
    	System.out.println(j);
	}
    public static void main(String args[])
    {
    	Overloading o=new Overloading();
    	o.overLoad(2, 3);
    	o.overLoad(1, 2, 3);
    } 
}

Output:
5
6

Having differences in the data types of the parameters or arguments we pass to a method.

Sample Code Snippet:

public class Overloading {
    public void overLoad(int x,int y)
	{
    	int i=x+y;
    	System.out.println(i);
	}
    public void overLoad(double x,double y)
	{
    	double j=x+y;
    	System.out.println(j);
	}
    public static void main(String args[])
    {
    	Overloading o=new Overloading();
    	o.overLoad(2, 3);
    	o.overLoad(5.0, 2.0);
    }
}

Output:
5
7.0

A Real time generic example of method overloading

Let’s say we are developing an application for which authentication is done with credentials like user name and password.

For this a method has been written in which the credentials are passed as method arguments. Now to make it more secure an option (user can choose it to enable or disable two step verification) must be provided at the login time to login with two step verification.

So in this case instead of writing a whole new method we use the existing method just by adding an extra parameters related to two step verification which enables code reusability without effecting the existing code.