任何人都可以详细解释在使用 Child 时调用重载方法 print(父父级)的原因在我的测试代码中的实例?
Can anybody explain in detail the reason the overloaded method print(Parent parent) is invoked when working with Child instance in my test piece of code?
这里涉及的Java中的任何虚拟方法或方法的重载/解决方案都是什么? 是否直接引用Java Lang Spec? 哪个术语描述了这种行为? 非常感谢。
Any pecularities of virtual methods or methods overloading/resolution in Java involved here? Any direct reference to Java Lang Spec? Which term describes this behaviour? Thanks a lot.
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); } }推荐答案
JLS在§8.4.9重载:
所以在你的情况下:
Java中不存在双重调度。你必须模拟它,例如使用访客模式。在这种模式中,基本上,每个子类实现一个 accept 方法,并使用 this 作为参数调用访问者,并且这个具有子类的编译时类型,因此使用了所需的方法重载。
Double dispatch does not exist in Java. You have to simulate it, e.g. by using the Visitor Pattern. In this pattern, basically, each subclass implements an accept method and calls the visitor with this as argument, and this has as compile-time type that subclass, so the desired method overloading is used.
更多推荐
Java方法重载+双重调度
发布评论