Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overloading

 
Donald Gatan
Greenhorn
Posts: 9
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Thanks.

Donald

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
Bartender
Posts: 4567
8
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Donald. Can you please post the reference to that question? Thanks.

To explain the answer...as 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
Greenhorn
Posts: 9
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic