Why is this the program's output?

public class OverloadingTest extends Format{

    public int add(String s1){
        System.out.println("With String");
        return 1;
    }
    public int add(Object a){
        System.out.println("With Object");
        return 1;
    }


    public static void main(String[] args) {
        OverloadingTest overloadingTest = new OverloadingTest();
        overloadingTest.add(null);
    }

}

Why is the output of the program With String ?

I have tried reading JLS for 6th Version, but I still could not find the answer.

The only reason I could guess is that the closest match in Inheritance hierarchy is chosen.

So in this case it would take String as Object is its super class.


This answer is available in the question Method Overloading for NULL parameter:

Java will always try to use the most specific applicable version of a method that's available (see JLS §15.12.2).

So, as a result, String is used, because it's the most specific type available. If more than one subtype exists, then you will have to cast null to the appropriate type to designate which function you want to run.


This is spelled out in §15.12.2.5. Choosing the Most Specific Method:

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

In your example, add(Object) can handle anything that add(String) can. This makes the latter more specific. It is therefore the one that gets chosen to handle null .


If more than one member method is both accessible and applicable to a method invocation ... The Java programming language uses the rule that the most specific method is chosen .

See The Java Language Specification

链接地址: http://www.djcxy.com/p/70880.html

上一篇: C#字典TryGetValue int值,如何避免双重查询

下一篇: 为什么这是该程序的输出?