Java Static and Dynamic Binding, Overloading

后端 未结 4 1342
-上瘾入骨i
-上瘾入骨i 2020-12-03 16:38

I am practicing for a test and I came across this exercise about overloading and static and dynamic binding. The output of the following code is asked:

class         


        
4条回答
  •  执念已碎
    2020-12-03 17:04

    Here is what's going on:

    stooge1.print(new Moe()); // All three have overload for Moe,
    // so the overload from the dynamic type of stooge1 gets called
    stooge1.print(new Curly()); // Compiler thinks stooge1 is Larry,
    // so it does not know that it has an overload for Curly.
    // It uses the overload for Larry instead, because Curly is a Larry
    stooge1.print(new Larry()); // Same logic as above applies.
    stooge2.print(new Curly()); // Compiler thinks stooge2 is Moe, so its only overload
    // is for Moe. Since the dynamic type is Larry, first overload is invoked
    

    The remaining three cases can be solved by applying the same logic as above.

提交回复
热议问题