Ahm*_*aya 46 java jvm bytecode
有三个操作码可以调用Java方法.很明显,invokeStatic仅用于静态方法调用.
据我所知,在调用构造函数和私有方法时使用了invokespecial.那么,我们是否需要在运行时区分私有和公共方法调用?可以使用相同的操作码调用invokevirtual来调用它吗?
JVM是否处理私有和公共方法定义?据我所知,在封装的开发阶段只需要公共和私有关键字?
Ahm*_*aya 23
http://www.artima.com/underthehood/invocationP.html 上面的链接提供了有价值的例子,清楚地说明了我的问题.
class Superclass {
private void interestingMethod() {
System.out.println("Superclass's interesting method.");
}
void exampleMethod() {
interestingMethod();
}
}
class Subclass extends Superclass {
void interestingMethod() {
System.out.println("Subclass's interesting method.");
}
public static void main(String args[]) {
Subclass me = new Subclass();
me.exampleMethod();
}
}
Run Code Online (Sandbox Code Playgroud)
当您在上面定义的Subclass中调用main()时,它必须打印"Superclass的有趣方法".如果使用invokevirtual,它将打印"Subclass的有趣方法".为什么?因为虚拟机会根据对象的实际类(即Subclass)选择调用interestingMethod().所以它将使用Subclass的interestingMethod().另一方面,使用invokespecial,虚拟机将根据引用的类型选择方法,因此将调用Superclass的interestingMethod()版本.
| 归档时间: |
|
| 查看次数: |
11234 次 |
| 最近记录: |