4.6 Overloading Methods and Constructors

Often
you'll want to have more than one function with the
same name. The most common example of this is to have more than one
constructor. In the examples shown so far, the constructor has taken
a single parameter: a DateTime object. It would be
convenient to be able to set new Time objects to
an arbitrary time by passing in year, month, date, hour, minute, and
second values. It would be even more convenient if some clients could
use one constructor, and other clients could use the other
constructor. Function overloading provides for exactly these
contingencies.

The signature of a method is defined by its name and
its parameter list. Two methods differ in their signatures if they
have different names or different parameter lists. Parameter lists
can differ by having different numbers or types of parameters. For
example, in the following code the first method differs from the
second in the number of parameters, and the second differs from the
third in the types of parameters:

As you can see, the Time class in Example 4-9 has two constructors. If a
function's signature consisted only of the function
name, the compiler would not know which constructors to call when
constructing t1 and t2.
However, because the signature includes the function argument types,
the compiler is able to match the constructor call for
t1 with the constructor whose signature requires a
DateTime object. Likewise, the compiler is able to
associate the t2 constructor call with the
constructor method whose signature specifies six integer arguments.

When you overload a method, you must change the signature (i.e., the
name, number, or type of the parameters). You are free, as well, to
change the return type, but this is optional. Changing only the
return type does not overload the method, and creating two methods
with the same signature but differing return types will generate a
compile error. This is illustrated in Example 4-10.

In this example, the Tester class overloads the
Triple( ) method, one to take an integer, the
other to take a long. The return type for the two Triple(
) methods varies. Although this is not required, it is very
convenient in this case.