1

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?

mzoz
  • 1,273
  • 1
  • 14
  • 28
  • "Linking" in Java is done at compile time based on the declared (static) type. – ernest_k Mar 17 '18 at 13:00
  • virtual method calls only applies to the left operand as the signature of the method is determined at compile time and doesn't change at runtime. This is to simplify method lookup esp i.e. you could have any number of combinations which could match other wise. – Peter Lawrey Mar 17 '18 at 13:04

1 Answers1

0

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:

  • Whose method, Dog's or Corgi's, needs to be called, and
  • In case of Corgi's methods, which overload needs to be called.

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Thanks for quick reply! Yes I totally understand the first decision part, for second decision I don't quite get what ''lock in at compile time'' means, do you mean in overloaded method selection process only static type of argument matters? (in contrast with in overridden method selection process dynamic type makes the final decision) – mzoz Mar 17 '18 at 13:23
  • @SouthParker That’s right, the decision on the overload is based only on static types of method arguments. – Sergey Kalinichenko Mar 17 '18 at 14:03
  • Cheers I also found the same answer in duplicate question. – mzoz Mar 18 '18 at 05:17