So i can pass nulls into functions in java. I can also overload functions in java. But consider the following
public static void main(String ... args){
doStuff(null);
}
public static void doStuff(String s){
solveWorldHunger();
}
public static void doStuff(Integer i){
nukeCanada();
}
public static void nukeCanada(){
System.out.println("NO!");
}
public static void solveWorldHunger(){
System.out.println("YAY!");
}
The previous program will always print out YAY no matter what the order of the sorce code…
Can anyone shed some light onto why the jvm consitently decides to run the solveWorldHunger function over the nukeCanada function`?
It’s quite clear to the compiler that you can’t store
nullin aprimitive int. So, it decides to go with the method which hasStringas argument.However, when you change your 2nd method to take
Integeras argument, then you will get compiler error. Because both of them are eligible to be invoked withnullargument. So, there will be ambiguity.So, try changing your 2nd method: –
And invoke it on
null. You will see the compiler error.So, in that case, you can invoke the appropriate method using typecasting like this: –
Also, note that, if you have your
2nd methodtake a parameter that is asuper typeofString, likeObject, then there would be no ambiguity, because compiler will now choose the most specific one, i.e.,Stringargument.So, ambiguity only occurs, when you have two methods with types that are not in the same inheritance hierarchy.