Compiler Construction/Java

Invocation
In Java, there are four kinds of method invocation, namely invokestatic, invokespecial, invokevirtual, invokeinterface. As the names suggest, the first is used to invoke static method and the rest instance methods. Since a static method cannot be overridden, invokestatic is very simple; it is essentially the same as calling a function in C.

We now see the mechanism of invocation of instance methods. Consider the following piece of code.

class A { public static int f { return 1; } private int g_private { return 2; } public final int g_final { return 3; } public int g_non_final { return 4; }

public void test (A a) { a.f ; // static; this is always 1. a.g_private ; // special; this is always 2. a.g_final ; // special; this is always 3. a.g_non_final ; // virtual; this may be 4 or something else. } }

class B extends A { public int g_non_final { return 6; } }

class C extends B { public int g_non_final { return 7; } public int foo { return A.this.g_non_final ; } }

invokestatic is invoked with the references to the class name and the method name and pops arguments from the stack. An expression  is complied to:

iconst_2          // push a constant 2 onto the stack invokestatic A.f  // invoke a static method // the return value is at the top of the stack.

In Java, a private method cannot be overridden. Thus, a method has to be called based on a class regardless of how an object is created. invokespecial allows this; the instruction is the same as invokestatic except that it also pops the object reference besides supplied arguments. Thus far, dynamic binding is not in use, and it is not necessary to have information about binding at runtime about private methods.

Specifically,  can be used either (1) calling a private method or (2) a invoking a method of the super class (including the constructor for the super class, namely ). To call a super method other than, one has to write like  where f is the name of the super method.

In semantics  doesn't differ from , but it can give the compiler a hit about the invocation.

Class methods
Class methods can be defined with a  qualifier. Private class methods may be in the same object, if they belong to the different classes. No two public class methods may be in the same object; in other words, class methods cannot be overridden. This also means  qualifier is semantically meaningless for class methods.

Fields
Each field is accessed based on a class. Consider the following.

class A { public int i = 2; } class B extends A { public int i = 3; }

B b = new B ; A a = b; b.i++; // this would be 3 + 1 = 4 a.i++; // this would be 2 + 1 = 3

In other words, an access control modifier (none, public, private and protected) only affects if clients of the class can access a given field. This means that Java virtual machine may ignore the access flag, handling each field in the same manner.