问题
I'm having trouble understanding this question, and the explanation of the answer for an SCJP 1.6 self test question. Here is the problem:
class A { }
class B extends A { }
public class ComingThru {
static String s = "-";
public static void main(String[] args) {
A[] aa = new A[2];
B[] ba = new B[2];
sifter(aa);
sifter(ba);
sifter(7);
System.out.println(s);
}
static void sifter(A[]... a2) { s += "1"; }
static void sifter(B[]... b1) { s += "2"; }
static void sifter(B[] b1) { s += "3"; }
static void sifter(Object o) { s += "4"; }
}
What is the result? The answer is -434, but what throws me off is the book's explanation. It is vastly different than how the concept was explained earlier in the chapter.
"In general, overloaded var-args methods are chosen last. Remember that arrays are objects. Finally, an int can be boxed to an Integer and then "widened" to an Object."
Splitting that up, can someone please further define that explanation?
- In general, overloaded var-args methods are chosen last.
- Arrays are objects (I actually get that, but why is that relevant to this question).
- An int can be boxed to an Integer and then "widened" to an Object.
Thanks!
回答1:
The book is trying to explain why the first two overloads are never selected: because the var-args marker ...
makes them be used only if every other possible overload fails. In this case, this doesn't happen -- the two sentences starting with "Remember" is explaining WHY it doesn't happen, why other possible overloads exists in the first and last case (the second case and its match with the 3rd overload of sifter is obvious): an array is an object, and an int can be boxened then widened to an Object, so the 4th overload matches the first and last ones of the calls to sifter.
回答2:
When attempting to determine which method to invoke, the compiler first looks for non vararg method (e.g.
sifter(Object)
) before considering a vararg one (e.g.sifter(A[]...)
), when both of the methods belong to the same class (more or less).Since an array is an
Object
, the invocation ofsifter(aa)
will matchsifter(Object)
, hence not even consideringsifter(A[]...)
.Starting from Java 5, the compiler may "box" primitive, i.e. convert primitive values (e.g.
int
) to their correspondingObject
(e.g.Integer
). So forsifter(6)
, the compiler converts theint 6
into anInteger 6
, thus it would match thesifter(Object)
method.
来源:https://stackoverflow.com/questions/1129282/var-arg-of-object-arrays-vs-object-array-trying-to-understand-a-scjp-self-te