File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Overloading Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Overloading" Watch "Overloading" New topic


Donald Gatan

Joined: Jun 16, 2011
Posts: 9

Hi Guys,

I tried to figure out the below codes but still i can't get the correct answer based on my simulation on paper.
The answer is letter D. How these codes derived the answer? Can anybody explain in a simple way.



3. class A { }
4. class B extends A { }
5. public class ComingThru {
6. static String s = "-";
7. public static void main(String[] args) {
8. A[] aa = new A[2];
9. B[] ba = new B[2];
10. sifter(aa);
11. sifter(ba);
12. sifter(7);
13. System.out.println(s);
14. }
15. static void sifter(A[]... a2) { s += "1"; }
16. static void sifter(B[]... b1) { s += "2"; }
17. static void sifter(B[] b1) { s += "3"; }
18. static void sifter(Object o) { s += "4"; }
19. }
What is the result?
A. -124
B. -134
C. -424
D. -434
E. -444
F. Compilation fails

® ✓ D is correct. 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.
Matthew Brown

Joined: Apr 06, 2010
Posts: 4544

Hi Donald. Can you please post the reference to that question? Thanks.

To explain the the explanation says, var-args always take the lowest precedence. So you'll only get a 1 or 2 in the output if none of the others match. And in these sort of overloading questions, you've got to be careful about the ones that take a single Object argument, as they'll catch all sort of things. In particular, an array IS-A object. And a primitive can be boxed to something that IS-A Object.

So the only call that doesn't match the fourth method is when you make the call with a B[] argument, as that matches precisely the third method. The most specific match wins.

Does that help? If that still doesn't make sense, explain what answer you've got as it might make it clearer what you're missing.
Donald Gatan

Joined: Jun 16, 2011
Posts: 9

My reference is book of SCJP 6 of Kathy and Bates chapter 2 self test. Thanks for the reply. I will try to figure out again...
I agree. Here's the link:
subject: Overloading
It's not a secret anymore!