Java Reference
In-Depth Information
Figure 5.3
The println() method is overloaded 10 times in the PrintStream class.
The PrintStream class has 10 println() methods. How does the compiler
know which one you want to invoke? If you look carefully, you will also notice
that the parameter list is different for each version of println(). For example,
calling println() and passing in an int invokes that overloaded version whose
signature is as follows:
public void println(int x)
Invoking println() and passing in a String invokes the following version:
public void println(String x)
If method overloading were not an option, the println() methods would
each have to use a unique name such as printlnInt(), printlnString(), println-
Double(), and so on. In this case, method overloading simplifies both the
writing of the PrintStream class and the usage of the class. Developers do not
need to remember 10 different names for printing a line of text to the system
output; they can simply remember that the method to use is println(), and it is
overloaded for every data type.
Let's look at an example using method overloading. The following Calcula-
tor class contains five multiply() methods. Study the method signatures care-
fully and determine whether this is valid method overloading.
public class Calculator
{
public int multiply(int x, int y)
{
Search WWH ::




Custom Search