Java方法分派说明:这两天遇到的一些Java方法分派的问题,结合自己书上看的,google的,还有撒迦教我的,做一个
Java方法分派
说明:这两天遇到的一些Java方法分派的问题,结合自己书上看的,google的,还有撒迦教我的,做一个总结吧.望指正.
?
class Super {
Super();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":
()V
4: return
void exampleMethod();
Code:
0: aload_0
1: ldc #5 // String aa
3:
invokespecial #6 // Method interestingMethod:(Ljava/l
ang/String;)I
6: pop
7: return
}
?
class Super {
Super();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":
()V
4: return
int interestingMethod(java.lang.String);
Code:
0: getstatic #2 // Field java/lang/System.out:Ljava/
io/PrintStream;
3: ldc #3 // String Super's interestingMethod
5: invokevirtual #4 // Method java/io/PrintStream.printl
n:(Ljava/lang/String;)V
8: iconst_1
9: ireturn
void exampleMethod();
Code:
0: aload_0
1: ldc #5 // String aa
3:
invokevirtual #6 // Method interestingMethod:(Ljava/l
ang/String;)I
6: pop
7: return
}
?
??? 两边的不同我通过加粗来说明了.正如撒迦说的,在Super类的exampleMethod方法中调用interestingMethod方法的指令是不同的,代码一采用的是invokespecial 而代码二采用的是invokevirtual .
?
public void sayHello(Human human){ System.out.println("human say hello"); }这个方法
在运行时进行动态分派,确定调用的是StaticDispatch实例的方法
是不是就可以说,虚函数的调用都是先在编译期进行静态分派,然后在运行时进行动态分派的呢?