Java - 方法选择算法
Java - Method picking algorithm
我正在研究方法并查看,如果我创建两个名为 "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");
}
输出每次都是"Bye",但我还是不明白这背后的逻辑。
在与 google 进行了短暂的研究后,没有任何解释,我决定在这里问这个问题。
希望有人能解释一下选择算法或者给我一个link给个解释
编译器更喜欢最专业的类型:
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 {
}
原因看一下this thread,@Hayden在评论里已经提到了
Java 将选择提供的两种方法中最具体的(参见 Java Language Specification)
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.
因为 Frame 的 class 层次结构是
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
Window 的 class 层次结构是
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
框架是最具体的方法,然后,您的public static void hello(Frame f)
将被选中。
我正在研究方法并查看,如果我创建两个名为 "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");
}
输出每次都是"Bye",但我还是不明白这背后的逻辑。 在与 google 进行了短暂的研究后,没有任何解释,我决定在这里问这个问题。
希望有人能解释一下选择算法或者给我一个link给个解释
编译器更喜欢最专业的类型:
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 {
}
原因看一下this thread,@Hayden在评论里已经提到了
Java 将选择提供的两种方法中最具体的(参见 Java Language Specification)
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.
因为 Frame 的 class 层次结构是
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
Window 的 class 层次结构是
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
框架是最具体的方法,然后,您的public static void hello(Frame f)
将被选中。