Using Anonymous Inner Classes

     

Method local inner classes define a class inside the body of a method. But you can also define a class as a method parameter. The anonymous inner class is called anonymous because it is never given a name .

The key distinguishing characteristic of anonymous inner classes is that they are declared and instantiated at the same time.

The most common place to see anonymous inner classes is in GUI event handlers. The idea is to keep the code that handles an event in the same place where the control is defined. You create them when you need a class that you only need to call from one place, when one specific thing happens. Because they're defined as part of a method, they must adhere to the same restrictions that method local inner classes do.

Here is an example:

 

 myButton.addActionListener(       new ActionListener() {            public void actionPerformed(                  ActionEvent e) {             //do the work here!             } //end actionPerformed method        }//end anonymous inner class ); //end addActionListener method call 

The addActionListener() method takes only one argument, of type ActionListener. ActionListener is an interface that listens for action events. You process action events in Swing by writing classes that implement this interface. After an object of that class is created, it is registered with a component using the addActionListener() method. That method is the same one that any class that implements the ActionListener interface would need to implement. So that is a little weird: it seems that you're making an instance of an interface, which you normally can't do. You can also do the same thing with abstract event adapter classes as well, such as WindowAdapter or MouseAdapter. It's the only place you're allowed to use the new operator on interfaces and abstract classes. That's because your anonymous class automatically becomes a subclass of that class.

The class can be anonymous because you'll never use this class again. It is okay ”perhaps even desirable ”that it has no name or definition outside of this context. The clicking of the myButton control is the only conceivable time you would want to invoke this code. Any other GUI control on your page is going to have to define its own action handler.



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net