Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: overloaded method resolution

So I have the following overloaded methods:

private static void foo(short... a)
{
    System.out.println("Calling var-len");
}

private static void foo(int a, int b)
{
    System.out.println("Calling int-int");
}

private static void foo(int a, double b) //(3)
{
    System.out.println("Calling int-double");
}

private static void main (String[] args)
{
    foo((short)2, (short)5); //This one outputs "Calling int-int"
}

I know that variable arity method has the lowest priority during method resolution phases, so in this case if I call foo((short)2, (short)4); I would get "Calling int-int".

HOWEVER, if I change method (3) to foo(short a, double b), the variable arity method is picked! (Java 7). Could anyone explain this?

like image 700
0x56794E Avatar asked Nov 27 '22 08:11

0x56794E


1 Answers

According to the specification:

http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2

"However, the declaration of a variable arity method (§8.4.1) can change the method chosen for a given method method invocation expression, because a variable arity method is treated as a fixed arity method in the first phase."

like image 73
Radiodef Avatar answered Dec 05 '22 05:12

Radiodef