Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Ambiguous method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Ambiguous method" Watch "Ambiguous method" New topic
Author

Ambiguous method

Animesh Shrivastava
Ranch Hand

Joined: Jul 19, 2004
Posts: 298
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

Joined: Jul 31, 2004
Posts: 61
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


SCJP 1.4, SCBCD 1.3<br />IBM 141, 484, 486
Animesh Shrivastava
Ranch Hand

Joined: Jul 19, 2004
Posts: 298
Hi Stefan,
I think thats very much clear,
Thanks for your reply.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Ambiguous method