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
The JLS states in §8.4.9 Overloading:
So in your case:
this
) is of compile-time type Parent
, and so the method print(Parent)
is invoked.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.
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
.