Java Reference
In-Depth Information
■
If a varargs method is overloaded, java uses the more specific version of the method instead of using a varargs
method. java uses varargs method as the last resort to resolve a method call.
Tip
Sometimes a call to an overloaded varargs method may cause confusion to the Java compiler. The overloading of
the method itself may be valid. However, the call to it may cause an issue. Consider the following snippet of code for
the
MathUtil7
class, which is a valid example of method overloading:
public class MathUtil7 {
public static int max(int...num) {
// Code goes here
}
public static int max(double...num) {
// Code goes here
}
}
Which version of the
max()
method will be called when the following statement is executed?
int max = MathUtil7.max(); // Which max() to call?
The above statement will generate a compilation time error stating that the call to
MathUtil7.max()
is
ambiguous. Java allows you to pass zero or more values for a variable-length argument. In the above statement,
both methods
max(int...num)
and
max(double...num)
qualify for the
MathUtil7.max()
call. The compiler cannot
decide which one to call. You may find many other instances where a call to an overloaded varargs method results in
an ambiguous method call and the compiler will generate an error. The error message will guide you to the
offending code.
Varargs Methods and the main() Method
Recall that if you want to run a class, you need to declare a
main()
method in it with a
String
array as its argument.
The signature for the
main()
method must be
main(String[] args)
. A varargs method is implemented by Java
compiler using an array. If your method signature is
m1(XXX...args)
, it is changed to
m1(XXX[] args)
by the
compiler. Now you can declare the
main()
method of your class using the older notation that uses a
String
array or
using a newer notation that uses a varargs. The following declaration of
main()
method for the
Test
class is valid. You
will be able to run the
Test
class using the
java
command.
public class Test {
public static void main(String...args) {
System.out.println("Hello from varargs main()...");
}
}