javapolymorphismdynamictype

Java argument with different static and dynamic types?


I'm learning cs61b Berkeley open course, and was puzzled with this question(question 1, line 7): https://sp18.datastructur.es/materials/discussion/examprep04sol.pdf

c.play(d);    // Method D is called

so in this case d has static type of Dog and dynamic type of Corgi, in compile-time Method D is recorded, then why in run-time it still calls Method D rather than Method E based on its dynamic type?


Solution

  • The point of the exercise was to test your understanding of using static and dynamic types for method dispatch.

    In your situation, Java compiler must make two decisions:

    The first decision is made based on the left side of the call expression c.play(d), i.e. c, which is Corgi. If Corgi is further subclassed into, say, Cardigan and Pembroke, the methods of the corresponding subclass would be called at runtime based on the dynamic type.

    The compiler is concerned only with the static type of c: it needs to make sure that play method taking Dog would be available at runtime. The virtual call itself is performed by JVM based on the dynamic type of the c object.

    The second decision, on which overload needs to be called, is also done at compile time. This is important, because it "locks in" the decision at compile time. That is why the right answer is "D", even though the object d has the dynamic type of Corgi.