![]() |
VOOZH | about |
Method Overloading in Varargs
Overloading allows different methods to have same name, but different signatures where signature can differ by number of input parameters or type of input parameters or both. We can overload a method that takes a variable-length argument by following ways:int varargsThis output is due to the fact that int is more specific than double. As specified in the JLS section 15.12.2.5, If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen according to type promotion. The following rules define the direct supertype relation among the primitive types in this case:
fun(int ...): Number of args: 3 Contents: 1 2 3 fun(String, int ...): Testing: 2 Contents: 10 20 fun(boolean ...) Number of args: 3 Contents: true false false
Varargs and Ambiguity
Sometimes unexpected errors can result when overloading a method that takes a variable length argument. These errors involve ambiguity because both the methods are valid candidates for invocation. The compiler cannot decide onto which method to bind the method call.fun(); // Error: Ambiguous!According to (JLS 15.2.2), there are 3 phases used in overload resolution: First phase performs overload resolution without permitting boxing or unboxing conversion, Second phase performs overload resolution while allowing boxing and unboxing and Third phase allows overloading to be combined with variable arity methods, boxing, and unboxing. If no applicable method is found during these phases, then ambiguity occurs. The call above could be translated into a call to fun(int …) or fun(boolean …). Both are equally valid and do not be resolved after all three phases of overload resolution because both the data types are different. Thus, the call is inherently ambiguous. Another example of ambiguity: The following overloaded versions of fun( )are inherently ambiguous:
static void fun(int ... a) { // method body }
static void fun(int n, int ... a) { //method body }
Here, although the parameter lists of fun( ) differ, there is no way for the compiler to resolve the following call:
fun(1)This call may resolve to fun(int ... a) or fun(int n, int ... a) method, thus creating ambiguity. To solve these ambiguity errors like above, we will need to forego overloading and simply use two different method names.