有人能详细解释一下,为什么在我的测试代码中使用 Child
实例时会调用重载方法 print(Parent parent)
的原因吗?
这里涉及到Java中虚拟方法或方法重载/解析的任何特殊之处吗? 是否有直接参考Java Lang Spec的内容? 哪个术语描述了这种行为? 非常感谢。
public class InheritancePlay {
public static class Parent {
public void doJob(Worker worker) {
System.out.println("this is " + this.getClass().getName());
worker.print(this);
}
}
public static class Child extends Parent {
}
public static class Worker {
public void print(Parent parent) {
System.out.println("Why this method resolution happens?");
}
public void print(Child child) {
System.out.println("This is not called");
}
}
public static void main(String[] args) {
Child child = new Child();
Worker worker = new Worker();
child.doJob(worker);
}
}