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 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
.