The compile time type ab
is just A
Therefore, when the compiler sees this expression:
ab.f(b)
... it only considers method signatures declared on A
and its superclasses (just Object
in this case).
So, the compiler decides to call a method with signature f(A a)
.
Now, at runtime, the VM chooses which implementation of this signature to execute based on the runtime type of the method invocation target, which is B
B
overrides f(A a)
, so the implementation override is called - and returns 2.
Basically, at compile time, an overload is determined to determine which method signature to call based on the compilation time types of both the invocation target and the arguments, and the redefinition is determined at runtime to develop an exact implementation to execute based on the runtime type of the target.
source share