• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Ambiguous method

 
Animesh Shrivastava
Ranch Hand
Posts: 298
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please look at the code below:

public class StrBuf {
public static void main(String[] args) {
StrBuf sb = new StrBuf();
sb.callMe(null);
}
void callMe(Object o) {
}

void callMe(String s) {
}

void callMe(char[] ch) {// Line 10
}
}

On compiling the above code i get the error as ambigious method call. But if i comment line 10, i dont get any such error. It compiles successfully.
Please anyone explain this behaviour

Thanks
Animesh
 
Stefan Guilhen
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Animesh

The method that will be invoked is decided at compile time. The problem is that you are invoking the callMe method passing null. When you have only

callMe(Object o) and callMe(String s)

the compiler will try to find the most narrow method that can handle null. Since String is a subclass of Object, it is the narrowest type that can handle the null parameter and you are fine.

But when you add callMe(char[] c) the compiler no longer can decide which is the narrowest type that can handle the null parameter. This happens because both char[] and String are subclasses of Object and none is a subclass of the other. That is, they are not in the same inheritance tree. If they were in the same inheritance tree the compiler would be able to find the narrowest type that could handle the null parameter.

If you want the code to compile, you have to cast the null parameter to the one of the types - e.g. callMe((String)null); Now the compiler can decide what method is to be called.

Hope this helps,
Stefan
 
Animesh Shrivastava
Ranch Hand
Posts: 298
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Stefan,
I think thats very much clear,
Thanks for your reply.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic