Max*_*Max 16 java oop overloading double-dispatch
任何人都可以详细解释在我的测试代码中print(Parent parent)
使用Child
实例时调用重载方法的原因吗?
这里涉及到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);
}
}
Run Code Online (Sandbox Code Playgroud)
Chr*_*rau 23
所以在你的情况下:
this
)是编译时类型Parent
,因此print(Parent)
调用该方法.Worker
该类是子类,并且子类将覆盖该方法,并且该worker
实例属于该子类,则将调用重写的方法.Java中不存在双重调度.您必须模拟它,例如使用访客模式.在这种模式中,基本上,每个子类实现一个accept
方法并使用this
as参数调用visitor ,并且this
具有子类的编译时类型,因此使用了所需的方法重载.
原因是它doJob
实现了Parent
而不是重载Child
.它传递this
给worker的print
方法,因为this
它是调用Parent
方法的类型Worker::print(Parent)
.
为了有Worker::print(Parent)
叫你needto超载doJob
在Child
:
public static class Child extends Parent {
public void doJob(Worker worker) {
System.out.println("from Child: this is " + this.getClass().getName());
worker.print(this);
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码this.getClass()
中Child
相当于Child.class
.