Java bytecode

Copy the following file into a file AClass.java.

public class AClass implements Comparable{
    protected int n;
    private static int counter = 0;

    public AClass(int n) throws Exception {
        if (tooMany()) throw new Exception("Over the limit");
        this.n = n;
        counter++;
    }

    private boolean tooMany() {
       return (counter >= 5);
    }

    public int getN() {
        return n;
    }

    public static void printCounter() {
        System.out.println(counter);
    }

    public int compareTo(Object other) {
        AClass otherA = (AClass) other;
        return n - otherA.n;
    }

    public static void main(String [] args) throws Exception {
        printCounter();
        AClass a1 = new AClass(1);
        AClass a2 = new AClass(2);
        Comparable c1 = a1;
        System.out.println(c1.compareTo(a2));
    }
}

Compile the program. At the command prompt type jclasslib, this starts the bytecode viewer. Choose "open" in the file menu and navigate to the AClass.class file. Open it in jclasslib.

In order to look at a method's code, click on Methods, then click on the method's name, and then on the code.

Open the code for main. By studying the bytecode and the source code please find at least one method called using the following:

  1. invokestatic
  2. invokespecial
  3. invokevirtual
  4. invokeinterface
In the answer please give the name of the method and the point where it was called.

Based on your observations please explain (briefly) when each of the four method call types is used.


Submit the answers to all questions.
CSCi 4651 home page