Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/399.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java方法选取算法_Java_Methods_Compiler Construction - Fatal编程技术网

Java方法选取算法

Java方法选取算法,java,methods,compiler-construction,Java,Methods,Compiler Construction,我在处理方法,并在寻找,如果我使用两个名为“hello”的方法,使用它们想要的不同对象,并将“null”传递给该方法,将执行哪个方法: public static void main(String... args) { hello(null); } public static void hello(Window w) { System.out.println("Hello"); } public static void

我在处理方法,并在寻找,如果我使用两个名为“hello”的方法,使用它们想要的不同对象,并将“null”传递给该方法,将执行哪个方法:

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

    public static void hello(Window w) {
        System.out.println("Hello");
    }

    public static void hello(Frame f) {
        System.out.println("Bye");
    }
每次输出都是“再见”,但我仍然不明白背后的逻辑。 在与谷歌进行了一次简短的研究之后,没有任何解释,我决定在这里提出这个问题


我希望有人能解释选择算法或给我一个链接来解释。

编译器更喜欢最专业的类型:

public class Parent {
    public static void main(String... args) {
        hello(null); // takes `Child`
    }

    public static void hello(Parent _) {
        System.out.println("SuperClass");
    }

    public static void hello(Child _) {
        System.out.println("SubClass");
    }
}

class Child extends Parent {

}

因此,看看@Hayden在评论中已经提到的方法。

Java将从提供的两种方法中选择最具体的方法(请参阅)

如果多个成员方法可访问且适用于 方法调用时,必须选择一个来提供 运行时方法分派的描述符。Java编程 语言使用的规则是选择最具体的方法

作为的类层次结构是

的类层次结构是


Frame是最具体的方法,然后,将选择您的
公共静态void hello(Frame f)

任何参考都将非常好!在这种情况下,此stackoverflow链接将非常有用-
java.lang.Object
    java.awt.Component
        java.awt.Container
            java.awt.Window
                java.awt.Frame
java.lang.Object
    java.awt.Component
        java.awt.Container
            java.awt.Window