Home arrow static arrow Java Programming [Archive] - question on method overloading
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - question on method overloading
This topic has 5 replies on 1 page.

Posts:47
Registered: 6/26/04
question on method overloading   
Jul 29, 2004 2:06 AM



 
public class Test{   public static void main(String args[]){  Test tes = new Test();  tes.call(null);} public void call(Object o){} public void call(String s){}  } 


why does it end up calling call(String s) ? why not call(Object o) ? Does it choose the one which is lowest on the hierarchy or something?
 

Posts:11,200
Registered: 7/22/99
Re: question on method overloading   
Jul 29, 2004 2:20 AM (reply 1 of 5)



 
Yes, the rule is "choose the method with the most specific argument list."

If it's not possible to decide which method has the most specific argument list you get a compile time error, like here:
public class Test{   public static void main(String args[]){  Test tes = new Test();  tes.call(null);}  public void call(Object o){} public void call(Integer i){} public void call(String s){} }
Test.java:6: reference to call is ambiguous, both method 
call(java.lang.Integer) in Test and method call(java.lang.String) in Test
match
tes.call(null);
^
1 error
 

Posts:5,965
Registered: 5/17/03
Re: question on method overloading   
Jul 29, 2004 2:26 AM (reply 2 of 5)



 
It seems to be possible to cast null and in this way control which method gets called,

call((Object)null);
 

Posts:4,496
Registered: 19/06/02
Re: question on method overloading   
Jul 29, 2004 2:50 AM (reply 3 of 5)



 
When you start using generics, due to type erasure, you will get a name clash with methods like:
public void someMethod(List<Integer> param)public void someMethod(List<String> param)
 

Posts:5,965
Registered: 5/17/03
Re: question on method overloading   
Jul 29, 2004 2:56 AM (reply 4 of 5)



 
When you start using generics, due to type erasure,
you will get a name clash with methods like:

Is this because generics in Java is implemented as a pre-processing step so the compiler will see List in both cases?
 

Posts:4,496
Registered: 19/06/02
Re: question on method overloading   
Jul 29, 2004 3:10 AM (reply 5 of 5)



 
Is this because generics in Java is implemented as a
pre-processing step so the compiler will see List in
both cases?

Yep. The compiler will "erase" the Integer and String types.
 
This topic has 5 replies on 1 page.