Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

How is ambiguity in selecting from overloaded methods resolved in Java?

package org.study.algos;
public class Study {

    public static void main(String[] args) {
       A a = new A();
       a.m1(null);
    }
 }
 class A {
    public void m1(String s) {
       System.out.println("String");
        System.out.println(s);
    }
    public void m1(Object obj) {
       System.out.println("Object");
       System.out.println(obj);
    }
}

Here, the output is

String null

Why does the JVM resolve the method to one with a String argument?

Thanks in advance J

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's a fairly elaborate algorithm, detailed in JLS 15.12. But the part that is relevant here is 15.12.2, which says "the most specific one is chosen." Both the Object and String overloads are "accessible and applicable" (the String is applicable because a null literal is a reference of all types), and the String is more specific.

EDIT: Corrected section, per Syntactic.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...