Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

left and right objects are evaluated / resolved during runtime or compile-time?

Referring to a book exercise...

Having the following code..

Left left = createLeftInstance ();
Right right = createRightInstance ();

...and keeping in consideration that both the above mentioned methods can return instance of all the sub-classes of Left and Right, in Java the call of the following method...

left.invoke (right);

how is resolved:

  • A) basing on runtime type of left and compile-time of right
  • B) basing on compile-time type of left and runtime of right
  • C) basing on compile-time type of left and compile-time of right
  • D) basing on runtime type of left and runtime of right
like image 714
Tim Daiu Avatar asked Jan 26 '26 02:01

Tim Daiu


1 Answers

Actually, I think that the technically correct answer is "none of the above".

  • At compile time, you need to know the declared types of the left variable (Left) and the right variable (Right). This will determine which method overload1 of the Left::invoke method is most applicable to a parameter of type Right.

  • At runtime, the actual type of left will determine which actual method gets called.

So the complete answer is:

E) based on compile-time AND runtime types of left and on the compile-time type of right.

However, I suspect that the point of this question in the textbook is to help you distinguish between compile-time resolution of non-overloaded methods and runtime method dispatching. For that purpose, A) is "correct enough".


1 - To make the determination, the compiler needs to compare Right and its supertypes with the different method overloads of the invoke method declared by Left and its supertypes. If there are multiple overloads, the compiler needs to choose the "most specific applicable" overload.

like image 104
Stephen C Avatar answered Jan 28 '26 15:01

Stephen C