Inner Local Classes

Inner local classes are perhaps the simplest of the nested classes to write, understand, and use. The following table shows how to create an inner local class. You simply write the declaration of your class in the usual way, and put it inside (local to) a block. The block almost always instantiates an object of the inner class.

Information on the local class is shown in Table 12-3.

Table 12-3. Local class

Java term

Description

Example code

Local class

This is an inner class.

It is local to a block, typically within a method.

void myMethod() {
    class MyLocal {
         /*code*/
         void something() { }
    }
    MyLocal m = new MyLocal();
    foo( m );
}

Qualities of an inner local class

A local class is an inner class. It is a class that is declared within a block of code, so it is not a member of the enclosing class. Typically, a local class is declared within a method.

A local class is not visible outside the block that contains it, but the block can create an object of the inner local class and give away a reference to it. Then the object lives on, and its methods can be invoked by whoever holds the reference.

Where to use an inner local class

Figure 12-2 shows a local class. This inner class is the event handler for a button. The overwhelming use of local classes is to create an object that can be called back as an event handler. The value that local classes add is that you can write the handler close to the code that creates the button (or whatever) that generates the events.

Figure 12-2. A local inner class

image

You can find this code example at www.afu.com/jj6, and you can try compiling and running it.

Example inner local class

You could easily convert this local class to a member class by moving it outside the method.

The distinction between member classes and local classes is a fine one. The most important limitation is that inner local classes can access only final variables or final parameters. The reason for this apparently strange restriction is given later in the chapter. It has to do with the way inner local classes are implemented.

To explain Figure 12-2 a little, an applet is a Java program that runs inside a browser. It is invoked by some HTML which I have put in the source code as a comment. If you browse this source file, the applet will start running.

Applets begin execution in a method called init(). You extend java.applet.Applet or javax.swing.JApplet and provide your own overriding init method. The init() method in this example contains an inner class that has a method which is called when the button is pressed. The method is the event handler for the button.

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

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