In this tutorial, we will learn how to implements methods overloading or function overloading in Java.
In Java, method overloading allows multiple methods with the same name but different parameter lists to coexist in the same class. This can involve variations in the number or types of parameters, or both. Overloaded methods provide flexibility by offering different ways to call a method, depending on the parameters passed.
void func() {}
void func(int a) {}
float func(double a) {}
float func(int a, float b) {}
In this example, the func()
method is overloaded with different parameter configurations. While the return types differ, this does not affect method overloading; overloading is purely based on parameters.
Consider the scenario where you need to sum numbers but could have different parameter requirements (e.g., 2 or 3 numbers). You could create separate methods like sum2(int, int)
and sum3(int, int, int)
. However, using method overloading allows a more readable approach by keeping the method name the same:
int sum(int a, int b) { ... }
int sum(int a, int b, int c) { ... }
Here, sum()
is overloaded to handle different numbers of arguments.
Method overloading can be achieved in two main ways:
class MethodOverloading {
private static void display(int a) {
System.out.println("Argument: " + a);
}
private static void display(int a, int b) {
System.out.println("Arguments: " + a + " and " + b);
}
public static void main(String[] args) {
display(1);
display(1, 4);
}
}
Argument: 1
Arguments: 1 and 4
class MethodOverloading {
private static void display(int a) {
System.out.println("Got Integer data.");
}
private static void display(String a) {
System.out.println("Got String object.");
}
public static void main(String[] args) {
display(1);
display("Hello");
}
}
Got Integer data.
Got String object.
In a utility class, you might use overloading to format numbers:
class HelperService {
private String formatNumber(int value) {
return String.format("%d", value);
}
private String formatNumber(double value) {
return String.format("%.3f", value);
}
private String formatNumber(String value) {
return String.format("%.2f", Double.parseDouble(value));
}
public static void main(String[] args) {
HelperService hs = new HelperService();
System.out.println(hs.formatNumber(500));
System.out.println(hs.formatNumber(89.9934));
System.out.println(hs.formatNumber("550"));
}
}
500
89.993
550.00
Tip: Constructor overloading in Java works similarly to method overloading.