How Inner Classes Are Compiled

You might be interested to learn that inner classes are completely defined in terms of a source transformation into corresponding freestanding classes, and that is how the Sun compiler compiles them. In other words, first it extracts them and pretends they are top-level classes with funny names. Then it fixes up the extra this pointers that are needed, and compiles them. The following is an inner class called pip:

public class orange {
     int i=0;
     void foo() {  }

     class pip {
          int seeds=2;
          void bar() { }
     }
}

Here's how the compiler transforms an inner class into JDK 1.0 compatible code. If you understand this process, a lot of the mystery of inner classes will disappear. First, extract the inner class, make it a top-level class, and prefix the containing-class-and-a-dollar-sign to its name.

class orange$pip {
     int seeds=2;
     void bar() { }
}
public class orange {
     int i=0;
     void foo() {  }
}

Then, give the inner class a private field this$0 that keeps a reference to the object in which it appears. Also, ensure all the constructors are passed an extra argument (the pointer to the containing instance) so they can initialize the this$0 field. Note: The name this$0 is reserved for internal use, so you can't completely replicate this process manually, but this is what the compiler is doing.

class orange$pip { // the transformed inner class
     private orange this$0;   // the saved copy of orange.this

     orange$pip(orange o) {  // constructor
          this$0 = o; // initialize the ref to enclosing obj
     }
     int seeds=2;
     void bar() { }
}

The manufactured field this$0 allows the inner class to access any fields of its containing class, even private fields that could not otherwise be accessed. If you try compiling this example, you will note that the compiler produces class files with names like orange$pip.class.

That embedded dollar sign in the name of nested classes is part of the definition. Having a consistent explicit policy for naming inner classes allows everyone's tools (debugger, linker, and so on) to work the same way. It's just a bit confusing that $ signs are also used by the Unix shell in shell variables.

We now finish the chapter by featuring the class Character.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.254.192