Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
608 views
in Technique[技术] by (71.8m points)

oop - Java method overloading + double dispatch

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?

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);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The JLS states in §8.4.9 Overloading:

  1. When a method is invoked (§15.12), the number of actual arguments (and any explicit type arguments) and the compile-time types of the arguments are used, at compile time, to determine the signature of the method that will be invoked (§15.12.2).
  2. If the method that is to be invoked is an instance method, the actual method to be invoked will be determined at run time, using dynamic method lookup (§15.12.4).

So in your case:

  1. The method argument (this) is of compile-time type Parent, and so the method print(Parent) is invoked.
  2. If the Worker class was subclassed and the subclass would override that method, and the worker instance was of that subclass, then the overridden method would be invoked.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...