Java method overloading + double dispatch

后端 未结 2 1856
故里飘歌
故里飘歌 2020-11-28 15:40

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

2条回答
  •  春和景丽
    2020-11-28 16:08

    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.

提交回复
热议问题