Why invokeSpecial is needed when invokeVirtual exists
There are three opcodes to invoke Java methods. It is clear that invokeStatic is just for static method invocation.
As far as I know invokespecial is used when invoking constructor and private methods. So, do we need to differenticate private and public method invocation at run time? It could be invoked with same opcode say invokevirtual?
Does JVM deals with private and public method definition? As far as I know public and private keywords is just needed at development phase for encapsulation?
From this site
The answer can be easily found if one reads the Java VM Spec carefully:
The difference between the invokespecial and the invokevirtual instructions is that invokevirtual invokes a method based on the class of the object. The invokespecial instruction is used to invoke instance initialization methods as well as private methods and methods of a superclass of the current class.
In other words, invokespecial is used to call methods without concern for dynamic binding, in order to invoke the particular class’ version of a method.
http://www.artima.com/underthehood/invocationP.html The link above gives valuable examples clearly which addresing my question.
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();
}
}
When you invoke main() in Subclass as defined above, it must print "Superclass's interesting method." If invokevirtual were used, it would print "Subclass's interesting method." Why? Because the virtual machine would choose the interestingMethod() to call based on the actual class of the object, which is Subclass. So it will use Subclass's interestingMethod(). On the other hand, with invokespecial the virtual machine will select the method based on the type of the reference, so Superclass's version of interestingMethod() will be invoked.