有人能详细解释一下在我的测试代码中使用Child
实例时调用重载方法print(Parent parent)
的原因吗?
这里涉及到虚方法或Java中的方法重载/解析的特性吗?有没有直接引用Java语言规范?哪个术语描述了这种行为?非常感谢。
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);
}
}
https://stackoverflow.com/questions/2794195
复制相似问题