java - 将 null 传递给首选 String 而不是 Object 的方法

标签 java string oop object

我在我的程序中遇到了一个问题,我用下面的一小段代码清楚地说明了这一点。谁能解释为什么会这样?

class ObjectnullTest {

    public void printToOut(String string) {

        System.out.println("I am null string");
    }


    public void printToOut(Object object)

        System.out.println("I am  null object");
    }



class Test {

    public static void main(String args[]) {

        ObjectnullTest a = new ObjectnullTest();
        a.printToOut(null);

    }
}

这总是打印 I am null string

我想知道原因,以便修改代码。

最佳答案

因为在方法重载的情况下

The most specific method is choosen at compile time.

因为“java.lang.String”是比“java.lang.Object”更特定的类型。在您的情况下,选择了将“String”作为参数的方法。

它在 JLS 中有明确记录:

The second step searches the type determined in the previous step for member methods. This step uses the name of the method and the types of the argument expressions to locate methods that are both accessible and applicable, that is, declarations that can be correctly invoked on the given arguments.

There may be more than one such method, in which case the most specific one is chosen. The descriptor (signature plus return type) of the most specific method is one used at run-time to perform the method dispatch.

关于java - 将 null 传递给首选 String 而不是 Object 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15046763/

相关文章:

java - 通过 BST 搜索

java - Apache POI 用于将文档转换为带脚注的 html

java - 计算单词中的字母出现次数

python - 重载运算符 __mul__ python

Java继承-如何设置子类实例的值以供其他子类共享(相同)?

java - OOP:具有依赖注入(inject)的可重用类

regex - 匹配空输入的 flex 脚本?

javascript - 可以从数组中的键中删除 HTML 标签吗?

java - 为什么我不能为方法返回的对象引用赋值?

java - 我无法使用 spring 框架将 Hibernate Validator 集成到 javaweb 项目中