Home > Java > javaTutorial > body text

Why Does Method Overloading Behave Differently with Null Values?

Susan Sarandon
Release: 2024-11-11 06:32:03
Original
446 people have browsed it

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);
    }
}
Copy after login

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);
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template