有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在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

为什么JVM将该方法解析为带有字符串参数的方法

提前谢谢 J


共 (5) 个答案

  1. # 1 楼答案

    字符串是对象,对象不是字符串,因此第一个重载比第二个重载更具体。见上文提到的JLS 15.12.2

  2. # 2 楼答案

    空值可以设置为任何类型的引用。 所有重载方法都在一个继承层次结构对象中<;-字符串,最不一般的一个正在被选择。 但是,如果有两个重载方法不在同一层次结构中,那么就会出现关于ambigous方法的编译错误

  3. # 3 楼答案

    这些方法是“重载的”,而不是“模糊的”

    根据Java Language Specification的说法:

    When a method is invoked (§15.12), the number of actual arguments (and any explicit type arguments) and the compile-time types of the arguments are used, at compile time, to determine the signature of the method that will be invoked (§15.12.2).

    第15.12.2条规定:

    There may be more than one such method, in which case the most specific one is chosen.

    StringObject更具体,因此虽然null与两者兼容,但选择了带有String参数的方法(当参数类型是类或接口层次结构的一部分时,会应用更复杂的规则)

  4. # 4 楼答案

    这是一个相当复杂的算法,详见JLS 15.12。但与此相关的部分是15.12.2,它表示“选择了最具体的一个。”对象和字符串重载都是“可访问且适用的”(字符串是适用的,因为空文本是所有类型的引用),而字符串更具体

    编辑:根据语法,更正部分