java - 将参数传递给重载函数的一些问题

标签 java arguments overloading

package java_coding;

public class String_Null {
public static void main(String[] args) {
    // TODO Auto-generated method stub
    String_Null string_Null = new String_Null();
    string_Null.method(null);
}

public void method(String string) {
    System.out.println("String");
}

public void method( Object object) {

    System.out.println("Object");
}


}

结果是字符串。解释为什么?

最佳答案

因为选择了最具体的方法,所以最具体的是String(与Object相比)。顺便说一句,这是在 JLS 中......我很快就会把它挖出来。

根据JLS

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 error.

关于java - 将参数传递给重载函数的一些问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52223537/

相关文章:

c - 函数和函数参数内部的 MPI 调用

Java Comparable,compareTo() 方法的多个/不同实现

C++ 在派生类中更改成员类型

java - 重载的构造函数

java - Tomcat Caused by : java. util.zip.ZipException: 打开zip文件时出错

java - 以编程方式为场景中的按钮设置 onClick 监听器

c++如何使函数(子例程)参数成为 double vector 或整数 vector

pythonic将变量转换为列表的方法

java - 计算 Tomcat/Spring Boot 上的传入/传出线程 - 未命中数

java - 通过java在snappy数据中插入json对象时出现错误