Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Overloading

 
Greenhorn
Posts: 9
Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
The whole point here is that the var-args methods are overloaded, because of that some rules of which method will execute will apply.

static void sifter(A[]... a2) { s += "1"; }

That means you can pass any number of argument A[] types or single A[][].
But when passing a single argument of type A[] java finds an overloaded method sifter(Object o) and because type A[] is an Object and the rule "Overloaded var-args methods are chosen last" the sifter(Object o) method is chosen instead of sifter(A[]... a2).

 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
(Duplicate of https://coderanch.com/t/543575/java/java/Overloading - I'll lock this version)
 
Don't get me started about those stupid light bulbs.
    Bookmark Topic Watch Topic
  • New Topic