Java method overloading + double dispatch

后端 未结 2 1853
故里飘歌
故里飘歌 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:17

    The reason is that doJob is implemented in Parent and not overloaded in Child. It passes this to the worker's print methos, because this is of the type Parent the method Worker::print(Parent) will be called.

    In order to have Worker::print(Parent) called you needto overload doJob in Child:

    public static class Child extends Parent {
        public void doJob(Worker worker) {
            System.out.println("from Child: this is " + this.getClass().getName());
    
            worker.print(this);
        }
    }
    

    In the code above this.getClass() in Child is equivalent to Child.class.

提交回复
热议问题