wood burning stoves 2.0*
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "Overloading" Watch "Overloading" New topic
Author

Overloading

Donald Gatan
Greenhorn

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.

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

Joined: Apr 06, 2010
Posts: 4344
    
    8

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

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...
 
wood burning stoves
 
subject: Overloading
 
Similar Threads
Self Test doubt
Overloading
kathy sierra self test question?
Study Guide 6 -- Chapter2 Self Test Question 15 on page 181.
SCJP 1.6 Chapter2 Question 15- Answer -> is D ,I think it should be E