Method Overloading and Null Value Parameter
Overloaded methods allow multiple methods with the same name but different parameter lists to coexist within a class. When calling an overloaded method, the compiler selects the most applicable method based on the parameter list passed. However, when a null value is passed as a parameter, a specific behavior occurs.
Consider the following code:
public class MoneyCalc { public void method(Object o) { System.out.println("Object Version"); } public void method(String s) { System.out.println("String Version"); } public static void main(String[] args) { MoneyCalc question = new MoneyCalc(); question.method(null); } }
In this code, upon passing null to the method method, the "String Version" is executed instead of "Object Version." This is because null can be implicitly converted to any class type, including String. Therefore, the compiler selects the method overload that most closely matches the inferred type of the null reference—in this case, String.
Now, modify the code slightly:
public class MoneyCalc { public void method(StringBuffer sb) { System.out.println("StringBuffer Version"); } public void method(String s) { System.out.println("String Version"); } public static void main(String[] args) { MoneyCalc question = new MoneyCalc(); question.method(null); } }
This time, an ambiguity occurs because both the StringBuffer and String methods are equally applicable to the null reference. Neither method is more specific than the other, so the compiler raises a compile-time error for this code.
The above is the detailed content of Why Does Method Overloading Behave Differently with Null Values?. For more information, please follow other related articles on the PHP Chinese website!