public static void main(String[] args) {
System.out.println(fun(2,3,4));
}
static int fun(int a,int b,int c)
{
return 1;
}
static int fun(int ... a)
{
return 0;
}
Output: 1
Question: In the above case why does the function fun select the 1st function and not the second.On what basis is the selection done since there is no way to determine which fun the user actually wanted to call ?
The inclusion of generics gives rise to a new type of error that you must guard against ambiguity. Ambiguity errors occur when erasure causes two seemingly distinct generic declarations to resolve to the same erased type, causing a conflict. Here is an example that involves method overloading.
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.
Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of values. This argument that can accept variable number of values is called varargs. The syntax for implementing varargs is as follows: accessModifier methodName(datatype… arg) { // method body }
The process of compiler trying to resolve the method call from given overloaded method definitions is called overload resolution. If the compiler can not find the exact match it looks for the closest match by using upcasts only (downcasts are never done). As expected the output is 10.
Basically there's a preference for a specific call. Aside from anything else, this means it's possible to optimize for small numbers of arguments, avoiding creating an array pointlessly at execution time.
The JLS doesn't make this very clear, but it's in section 15.12.2.5, the part that talks about a fixed arity method being more specific than another method if certain conditions hold - and they do in this case. Basically it's more specific because there are more calls which would be valid for the varargs method, just as if there were the same number of parameters but the parameter types themselves were more general.
Compiler always selects the precise method when these kind of ambiguities are encountered. In your scenario func with three arguments is more precise than the variable arguments one so that is called.
EDIT: Edited as per skeet's comment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With