Java Reference
In-Depth Information
When the compiler encounters a method call, it attempts to locate a method declara-
tion with the same name and with parameters that match the argument types in the call.
In this example, each
printArray
call matches one of the
printArray
method declara-
tions. For example, line 14 calls
printArray
with
integerArray
as its argument. The
compiler determines the argument's type (i.e.,
Integer[]
) and attempts to locate a
print-
Array
method that specifies an
Integer[]
parameter (lines 22-29), then sets up a call to
that method. Similarly, when the compiler encounters the call at line 16, it determines the
argument's type (i.e.,
Double[]
), then attempts to locate a
printArray
method that spec-
ifies a
Double[]
parameter (lines 32-39), then sets up a call to that method. Finally, when
the compiler encounters the call at line 18, it determines the argument's type (i.e.,
Char-
acter[]
), then attempts to locate a
printArray
method that specifies a
Character[]
parameter (lines 42-49), then sets up a call to that method.
Common Features in the Overloaded
printArray
Methods
Study each
printArray
method. The array element type appears in each method's header
(lines 22, 32 and 42) and
for
-statement header (lines 25, 35 and 45). If we were to replace
the element types in each method with a generic name—
T
by convention—then all three
methods would look like the one in Fig. 20.2. It appears that if we can replace the array
element type in each of the three methods with a
single generic type
, then we should be able
to declare
one
printArray
method that can display the
String
representations of the ele-
ments of
any
array that contains objects. The method in Fig. 20.2 is similar to the generic
printArray
method declaration you'll see in Section 20.3. The one shown here
will not
compile
—we use this simply to show that the three
printArray
methods of Fig. 20.1 are
identical except for the types they process.
1
public static void
printArray( [] inputArray)
T
2
{
3
// display array elements
4
for
( element : inputArray)
T
5
System.out.printf(
"%s "
, element);
6
7
System.out.println();
8
}
Fig. 20.2
|
printArray
method in which actual type names are replaced with a generic type
name (in this case
T
).
Time Translation
If the operations performed by several overloaded methods are
identical
for each argument
type, the overloaded methods can be more conveniently coded using a generic method.
You can write a single generic method declaration that can be called with arguments of
different types. Based on the types of the arguments passed to the generic method, the
compiler handles each method call appropriately. At
compilation time
, the compiler en-
sures the
type safety
of your code, preventing many runtime errors.
Figure 20.3 reimplements Fig. 20.1 using a generic
printArray
method (lines 22-29
of Fig. 20.3). The
printArray
calls in lines 14, 16 and 18 are identical to those of