Java方法重载+双重调度

2024-03-28

谁能详细解释一下重载方法的原因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);
    }
}

JLS 指出§8.4.9 重载 http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.4.9:

  1. 当调用方法时(第 15.12 节),实际参数的数量(以及任何显式类型参数)和参数的编译时类型在编译时用于确定将调用的方法的签名(第 15.12.2 节)。
  2. 如果要调用的方法是实例方法,则将在运行时使用动态方法查找(第 15.12.4 节)确定要调用的实际方法。

所以在你的情况下:

  1. 方法参数 (this) 是编译时类型Parent,所以该方法print(Parent)被调用。
  2. If the Worker类被子类化,子类将重写该方法,并且worker实例是该子类的,那么将调用重写的方法。

Java 中不存在双重调度。你必须模拟它,例如通过使用访客模式 http://en.wikipedia.org/wiki/Visitor_pattern。在这种模式中,基本上,每个子类都实现一个accept方法并调用访问者this作为参数,并且this具有该子类的编译时类型,因此使用所需的方法重载。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java方法重载+双重调度 的相关文章

随机推荐