Method Overloading

Method names are very important and should reflect what the methods do. In many circumstances, you may want to use the same name for multiple methods because they have similar functionality. For instance, the method printString may take a String argument and prints the string. However, the same class may also provide a method that prints part of a String and accepts two arguments, the String to be printed and the character position to start printing from. You want to call the latter method printString too because it does print a String, but that would be the same as the first printString method.

Thankfully, it is okay in Java to have multiple methods having the same name, as long as each method accept different sets of argument types. In other words, in our example, it is legal to have these two methods in the same class.

public String printString(String string)
public String printString(String string, int offset)

This feature is called method overloading.

The return value of the method is not taken into consideration. As such, these two methods must not exist in the same class:

public int countRows(int number);
public String countRows(int number);

This is because a method can be called without assigning its return value to a variable. In such situations, having the above countRows methods would confuse the compiler as it would not know which method is being called when you write

System.out.println(countRows(3));.

A trickier situation is depicted in the following methods whose signatures are very similar.

public int printNumber(int i) {
    return i*2;
}
public long printNumber(long l) {
    return l*3;
}

It is legal to have these two methods in the same class. However, you might wonder, which method is being called if you write printNumber(3)?

The key is to recall from Chapter 2, “Language Fundamentals” that a numeric literal will be translated into an int unless it is suffixed L or l.. Therefore, printNumber(3) will invoke this method:

public int printNumber(int i)

To call the second, pass a long:

printNumber(3L);

System.out.print() (and System.out.println()) is an excellent example of method overloading. You can pass any primitive or object to the method because there are nine overloads of the method. There is an overload that accepts an int, one that accepts a long, one that accepts a String, and so on.

Note

Static methods can also be overloaded.