我知道重载使用静态绑定(bind)而覆盖使用动态绑定(bind)。 但是,如果它们混合在一起呢? 根据this tutorial , 为了解析方法调用,静态绑定(bind)使用类型信息,而动态绑定(bind)使用实际的对象信息。
那么,下面的例子中是否发生静态绑定(bind)来确定调用哪个sort()
方法?
public class TestStaticAndDynamicBinding {
@SuppressWarnings("rawtypes")
public static void main(String[] args) {
Parent p = new Child();
Collection c = new HashSet();
p.sort(c);
}
}
.
public class Parent {
public void sort(Collection c) {
System.out.println("Parent#sort(Collection c) is invoked");
}
public void sort(HashSet c) {
System.out.println("Parent#sort(HashSet c) is invoked");
}
}
.
public class Child extends Parent {
public void sort(Collection c) {
System.out.println("Child#sort(Collection c) is invoked");
}
public void sort(HashSet c) {
System.out.println("Child#sort(HashSet c) is invoked");
}
}
附言:
输出是:
Child#sort(Collection c) 被调用
最佳答案
如您所料,这里有两个绑定(bind)阶段。
首先,静态阶段,将选择调用sort(Collection c)
。这是在编译时完成的,因为 c
是 Collection
类型的引用,所以无论运行时类型如何(它是一个 哈希集
).
然后,在运行时,由于 p
实际上包含一个 Child
实例,它的方法将被调用,你将得到 "Child#sort(Collection c) 被调用"
。
关于java - case : static binding? 动态绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31086032/