Home  >  Article  >  Java  >  Why Does Method Overloading Behave Differently with Null Values?

Why Does Method Overloading Behave Differently with Null Values?

Susan Sarandon
Susan SarandonOriginal
2024-11-11 06:32:03452browse

Why Does Method Overloading Behave Differently with Null Values?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn