0

Suppose we have:

  1 public class DynamicDispatch {
  2     public static void main(String[] args) {
  3         Fish f = new BlueFish();
  4         f.speak();
  5     }
  6 }
  7 
  8 abstract class Fish {
  9     abstract String speak();
 10 }
 11 
 12 class BlueFish extends Fish {
 13     String speak() {
 14         return "I am a blue fish";
 15     }
 16 }
 17 
 18 class CatFish extends Fish {
 19     String speak() {
 20         return "I am a cat fish";
 21     }
 22 }

Question:

  1. From the assembly, a BlueFish object was created. But why the javac didn't realize that BlueFish.speak() should be invoked?

  2. During runtime, how does the JVM handle invokespecial #4, so that the right target wil be called?

FYI, the javap -c output is:

Compiled from "DynamicDispatch.java"
public class DynamicDispatch extends java.lang.Object{
public DynamicDispatch();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   new #2; //class BlueFish
   3:   dup
   4:   invokespecial   #3; //Method BlueFish."<init>":()V
   7:   astore_1
   8:   aload_1
   9:   invokevirtual   #4; //Method Fish.speak:()Ljava/lang/String;
   12:  pop
   13:  return

}
JackWM
  • 10,085
  • 22
  • 65
  • 92
  • 6
    You could just compile it and take a look at the resulting bytecode... – Oliver Charlesworth Jul 12 '13 at 00:40
  • 1
    the object instance has a virtual method table that is looked up at runtime. The table is built when the object is instantiated so is specific to the type of the object. Javac does not need to know what the object type is all it does is select method number 4 from the table. – BevynQ Jul 12 '13 at 00:55
  • @BevynQ Could you point out some references about Java's virtual method table? Thanks! – JackWM Jul 12 '13 at 00:59
  • http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.invokevirtual – BevynQ Jul 12 '13 at 01:01

1 Answers1

0

Answer:

  1. javac doesn't try to realize it, becuase it would be easy to make a situation where javaccouldn't find out as easily, or even at all. You might find out whether to use CatFish or BlueFish using user input, for example.

  2. For this, see BevynQ's comment. I'm surprised he didn't add it as an answer.

tbodt
  • 16,609
  • 6
  • 58
  • 83