Maria Kowalczyk wrote:
This code prints long.
Why is that? How did compiler decided that it likes long version of foo() method the most.
If I had to guess I'd pick int... or possibly Integer as they are most similiar to what was passed.
But why long?
There are two rules that apply here...
First, if more than one method match, the compiler will try to look for the "most specific" method. How that works is... let's say two methods match, now, which is the most specific? The answer is... if you take the parameters of one of the methods, and can use it to call the the other method, and it works (without explicit casting), but the reverse doesn't work, then that method is more specific than the other -- and it gets chosen.
Second, for backward compatibility, not all options are tried straight away. It is done in three passes. The first pass only uses typing. The second pass uses method conversion (which doesn't include varargs). And the third pass uses everything.
So... using the second rule. On the first pass, the only method that matches is the one that takes a long, as autoboxing and var-args don't apply yet. And since, there is only one match, no need to look for the more specific.
Henry