Java Reference
In-Depth Information
As with any new feature of the language, expect variable-length
arguments to be on the exam. Remember that a method can only declare
one parameter as variable-length, and it must appear at the end of the
parameter list.
Variable-length arguments can sometimes lead to ambiguities in method overloading
when the compiler cannot determine which method to invoke. For example, a class could
legally declare the following two methods named average :
public static int average(int... values)
public static double average(double... values)
Invoking average with a list of doubles works fi ne:
average(12.5, -4.78, 39.04); //works fine
However, any attempt to invoke the average method with a list of ints generates a
compiler error:
average(6, 10, 14, 20); //does not compile
Here is the compiler error from this statement:
MyMath.java:12: reference to average is ambiguous, both method average(int...)
in MyMath and method average(double...) in MyMath match
average(6, 10, 14, 20);
The same compiler error occurs when you attempt to invoke average with no
arguments:
average(); //ambiguous!
When using variable-length arguments and method overloading, you need to ensure that
the data types of your parameter lists are unique enough to avoid any ambiguities.
Method Overloading
Method overloading is when a class contains multiple methods with the same name but
different parameter lists. Constructors can also be overloaded. We use method overloading
all the time in Java. It is easier than trying to come up with different names for methods
that perform similar tasks but require different types of data to be passed in. This section
discusses the details of method overloading.
Search WWH ::




Custom Search