Monday, October 27, 2008

java method ambiguous exception

All about the java method ambiguous exception is bit tricky..
When JVM throws java.lang.Error: Unresolved compilation problem: The method is ambiguous?
This compilation problem occurs while method overloading,
for example:-
we have a class with two overloaded methods like
public static void overloadMeth(Integer i){
//do some stuff
}
public static void overloadMeth(String s){
//do some stuff
}
this is fine, but while you are trying to call this method
overloadMeth(null);
by passing 'null' then the method ambiguous exception will be thrown by JVM,
because if JVM allow us to compile this method call, at runtime JVM cant decide witch method to be invoke either method with String arg i.e overloadMeth(String s) or method withInteger arg i.e overloadMeth(Integer i)
If those two methods arguments are in inheritance hirarchy,
ex:
public static void overloadMeth(Object o){
//do some stuff
}
public static void overloadMeth(String s){
//do some stuff
}
now Object and String are in an inheritance hirarchy, while you invoke method(null) by passing null, the method with String arg will be invoked (last subclass in the hirarchy ll be called).

No comments: