Overloading Methods
suggest changeSometimes the same functionality has to be written for different kinds of inputs. At that time, one can use the same method name with a different set of parameters. The method name and the parameter types form the signature. As the example shows, several methods can share a name.
public class Displayer {
public void displayName(String firstName) {
System.out.println("Name is: " + firstName);
}
public void displayName(String firstName, String lastName) {
System.out.println("Name is: " + firstName + " " + lastName);
}
public static void main(String[] args) {
Displayer displayer = new Displayer();
displayer.displayName("Ram"); //prints "Name is: Ram"
displayer.displayName("Jon", "Skeet"); //prints "Name is: Jon Skeet"
}
}
The advantage is that the same functionality is called with two different numbers of inputs. While invoking the method according to the input we are passing, (In this case either one string value or two string values) the corresponding method is executed.
Methods can be overloaded:
- Based on the number of parameters passed.
Example: method(String s) and method(String s1, String s2).
- Based on the order of parameters.
Example: method(int i, float f) and method(float f, int i).
Note: Methods cannot be overloaded by changing only the return type. int method() and String method() have the same signature and are not legal in one class. The compiler rejects that; it is not a RuntimeException. To overload a method, change the parameter list.