Left and right objects evaluated/parsed at runtime or compile time?
Refers to book exercises….
There is the following code:
Left left = createLeftInstance ();
Right right = createRightInstance ();
… And considering that both of the above methods can return instances of all subclasses of Left and Right, call the following method in Java….
left.invoke (right);
How to solve it:
- A) Based on the runtime type on the left and the compile-time type on the right
- B) Based on the compile-time type on the left and the runtime type on the right
- left and the compile-time type on the right
- D) Based on the left runtime type and the right runtime
C) Based on the compile-time type on the
Solution
Actually, I think the technically correct answer is “none of the above”.
At compile time, you need to know
the left
variable (Left
) andthe right
variable (correct
). This determines which method overload of theLeft::invoke
method best applies to parameters of type Right.At run time, the actual type
of left
determines which actual method is called.
So the full answer is:
E) based on compile-time AND runtime types of
left
and on the compile-time type ofright
.
However, I suspect that the point of this issue in textbooks is to help you distinguish between compile-time parsing and run-time method dispatch for non-overloaded methods. For this, A) is “correct enough”.
1 – In order to make a decision, the compiler needs to compare the Right
and its parent (super class) type with the different method overloads of the
and its parent (super class) type. If there are multiple overloads, the compiler needs to select the overload that applies most. declared invoke
method Left