首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Java方法重载+双重调度

Java方法重载+双重调度
EN

Stack Overflow用户
提问于 2010-05-08 21:14:08
回答 1查看 4.9K关注 0票数 17

有人能详细解释一下在我的测试代码中使用Child实例时调用重载方法print(Parent parent)的原因吗?

这里涉及到虚方法或Java中的方法重载/解析的特性吗?有没有直接引用Java语言规范?哪个术语描述了这种行为?非常感谢。

代码语言:javascript
复制
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);
    }
}
EN

回答 1

Stack Overflow用户

发布于 2010-05-08 21:23:22

原因是doJob是在Parent中实现的,而不是在Child中重载。它将this传递给工作者的print方法,因为this的类型是Parent,方法Worker::print(Parent)将被调用。

为了调用Worker::print(Parent),您需要在Child中重载doJob

代码语言:javascript
复制
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

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2794195

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档