java 单参数方法重载

java method overloading with single argument

public class HelloWorld{
     public static void main(String []args){
        new SampleString().add(null);
     }
}

class SampleString{
    public void add(Object s){
        System.out.println("Inside Object method");
    }
    public void add(String s){
        System.out.println("Inside string method");
    }
}

为什么程序打印 "Inside string method" 而不是 "Inside Object method" ? 你能解释一下这背后的逻辑吗?

编译器根据传递给方法的参数类型选择最具体的实现。

来自 Java 语言规范 section on determining compile-time method signature:

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.

它将选择适用的最高级别类型。由于 String 扩展了 Object,它成为最高级别。如果你用不是字符串的东西调用它,它应该使用对象 one