为什么以及如何编译此Java代码?

Jon*_*oin 10 java

以下代码打印"String"

public class Riddle {

    public static void main(String[] args) {
        hello(null);
    }

    public static void hello(Object o) {
        System.out.println("Object");
    }


    public static void hello(String s) {
        System.out.println("String");
    }

}
Run Code Online (Sandbox Code Playgroud)

为什么代码编译?是不是暧昧?

例如,由于签名模糊,以下代码将无法编译.

public class Riddle {

    public static void main(String[] args) {
        hello(null);
    }

    public static void hello(Object o) {
        System.out.println("Object");
    }

    public static void hello(Integer o) {
        System.out.println("Integer");
    }

    public static void hello(String s) {
        System.out.println("String");
    }

}
Run Code Online (Sandbox Code Playgroud)

有人可以解释为什么第一个例子可以编译而没有模棱两可的错误?

Ris*_*shi 1

在第二种情况下,编译器无法编译,因为编译器无法在采用整数的方法和采用字符串的方法之间做出决定,而在第一种情况下,编译器可以弄清楚。

参考:http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2