如何在Java中解决重载方法的选择歧义? [英] How is ambiguity in selecting from overloaded methods resolved in Java?

查看:128
本文介绍了如何在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);
    }
}

此处输出为


String
null

String null

为什么JVM解析一个带String参数的方法?

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

提前谢谢
J

Thanks in advance J

推荐答案

这是一个相当精细的算法,详见 JLS 15.12 。但是这里相关的部分是 15.12.2 ,其中说选择最具体的一个。 Object和String重载都是可访问且适用的(String是适用的,因为null文字是所有类型的引用),而String更具体。

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.

编辑:根据句法修正部分。

Corrected section, per Syntactic.

这篇关于如何在Java中解决重载方法的选择歧义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆