In Java, the concept of "overloading" is when two or more methods of a class have the same name but different "parameter lists". In this special case, when a method is called, the program calls the correct method by checking the parameters. To understand this concept further, let's think back to when we were working with the Math
class. When we used the method Math.abs()
, we experienced the concept of overloading as the method had four different choices for the parameter; the data types int
, double
, float
, and long
. Let's dive into how we can overload a method.
package exlcode;
public class OverloadingMethodsExample {
public static float exampleVariableOne = 3.14f;
public static double exampleVariableTwo = Math.PI;
public static void main(String[] args) {
print(exampleVariableOne);
print(exampleVariableTwo);
}
// two identical methods with different parameters
// takes in float value as a parameter
public static void print(float parameterOne) {
System.out.println("float: " + parameterOne);
}
// takes in a double value as a parameter
public static void print(double parameterOne) {
System.out.println("double: " + parameterOne);
}
}
The method named print()
is overloaded when we create two methods with the same name containing different parameters. One takes in double
values while the other takes float
values. The only difference between the methods has to be the parameters in order for it to be considered "overloading". One rule to keep in mind when working with overloaded methods is that return types for the methods cannot be the only thing that separates one method from the other. For example, creating two methods with the headers public int methodA()
and public double methodA()
will result in an error.