有人能详细解释一下在我的测试代码中使用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);
}
}
发布于 2010-05-08 21:23:22
原因是doJob
是在Parent
中实现的,而不是在Child
中重载。它将this
传递给工作者的print
方法,因为this
的类型是Parent
,方法Worker::print(Parent)
将被调用。
为了调用Worker::print(Parent)
,您需要在Child
中重载doJob
public static class Child extends Parent {
public void doJob(Worker worker) {
System.out.println("from Child: this is " + this.getClass().getName());
worker.print(this);
}
}
在上面的代码中,Child
中的this.getClass()
等同于Child.class
。
https://stackoverflow.com/questions/2794195
复制相似问题