Method overloading happens when you have more than one method with the same name in the same class, but the methods have different parameter lists.
This allows a programmer to use the same method name for similar actions.
Method overloading makes programs:
Instead of creating many different method names, you can reuse one method name for similar tasks.
public class MathExample
{
public int add(int a, int b)
{
return a + b;
}
public int add(int a, int b, int c)
{
return a + b + c;
}
public double add(double a, double b)
{
return a + b;
}
}
In this class, the method name is always add, but each version has a different parameter list.
For methods to be overloaded, they must differ by:
printInfo(String name)
printInfo(String name, int age)
showValue(int x)
showValue(double x)
display(String name, int grade)
display(int grade, String name)
Changing only the return type does not overload a method.
public int test(int x)
public double test(int x)
These methods have the same name and same parameter list, so Java gets confused.
Java looks at the arguments in the method call and matches them to the correct overloaded method.
public class Demo
{
public void greet()
{
System.out.println("Hello!");
}
public void greet(String name)
{
System.out.println("Hello, " + name);
}
}
Method calls:
greet(); // calls greet()
greet("Maria"); // calls greet(String name)
public class Calculator
{
public int multiply(int a, int b)
{
return a * b;
}
public int multiply(int a, int b, int c)
{
return a * b * c;
}
public double multiply(double a, double b)
{
return a * b;
}
}
This lets the programmer use the same method name, multiply, in different situations.
Students sometimes think these are overloaded:
public void example(int x)
public void example(int y)
public class OverloadExample
{
public void showMessage()
{
System.out.println("Welcome!");
}
public void showMessage(String name)
{
System.out.println("Welcome, " + name + "!");
}
public void showMessage(String name, int age)
{
System.out.println("Welcome, " + name + ". You are " + age + " years old.");
}
public static void main(String[] args)
{
OverloadExample obj = new OverloadExample();
obj.showMessage();
obj.showMessage("Jordan");
obj.showMessage("Jordan", 16);
}
}
Welcome!
Welcome, Jordan!
Welcome, Jordan. You are 16 years old.
It helps make code cleaner and easier to understand.