img
public static void main(String args[])
{
vaTest(1, 2, 3);
vaTest("Testing: ", 10, 20);
vaTest(true, false, false);
}
}
The output produced by this program is shown here:
vaTest(int ...): Number of args: 3 Contents: 1 2 3
vaTest(String, int ...): Testing: 2 Contents: 10 20
vaTest(boolean ...) Number of args: 3 Contents: true false false
This program illustrates both ways that a varargs method can be overloaded. First, the
types of its vararg parameter can differ. This is the case for vaTest(int ...) and vaTest(boolean
...). Remember, the ... causes the parameter to be treated as an array of the specified type.
Therefore, just as you can overload methods by using different types of array parameters,
you can overload vararg methods by using different types of varargs. In this case, Java uses
the type difference to determine which overloaded method to call.
The second way to overload a varargs method is to add a normal parameter. This is what
was done with vaTest(String, int ...). In this case, Java uses both the number of arguments and
the type of the arguments to determine which method to call.
NOTE  A varargs method can also be overloaded by a non-varargs method. For example, vaTest(int x)
OTE
is a valid overload of vaTest( ) in the foregoing program. This version is invoked only when one
int argument is present. When two or more int arguments are passed, the varargs version
vaTest(int...v) is used.
Varargs and Ambiguity
Somewhat unexpected errors can result when overloading a method that takes a variable-length
argument. These errors involve ambiguity because it is possible to create an ambiguous call to
an overloaded varargs method. For example, consider the following program:
// Varargs, overloading, and ambiguity.
//
// This program contains an error and will
// not compile!
class VarArgs4 {
static void vaTest(int ... v) {
System.out.print("vaTest(int ...): " +
"Number of args: " + v.length +
" Contents: ");
for(int x : v)
System.out.print(x + " ");
System.out.println();
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home