Overloading Methods

suggest change

Sometimes 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. Each different set of parameters is known as a method signature. As seen per the example, a single method can have multiple signatures.

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:

  1. Based on the number of parameters passed.

Example: method(String s) and method(String s1, String s2).

  1. 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 just* the return type (int method() is considered the same as String method() and will throw a RuntimeException if attempted). If you change the return type you must also change the parameters in order to overload.*

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Classes and Objects:
* Overloading Methods

Table Of Contents
8 Arrays
10 Maps
11 Strings
14 Classes and Objects
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap