Tuesday 26 November 2013

Anonymous Inner Class


An anonymous inner class is really a inner class with no name. They can be used when you only want to make one instance of the class. The use of an anonymous inner class can be a compact way of implementing an event listener:

JButton equalsButton = new JButton("=");
equalsButton.setActionCommand("=");
equalsButton.addActionListener(new ActionListener()
{
     @Override
     public void actionPerformed(ActionEvent event)
      {
            //the code here is executed when the button is clicked.
      }
});
In the above code a JButton is created and instead of assigning a class which implements the ActionListener interface using the addActionListener method we instead write the class itself. The class has no need of a name as it only gets called in the one place. The code for the button click is placed in the actionPerformed method which has the advantage of making it more maintainable because of it's right next to where the button is declared.

Although the syntax might look a llittle more complicated it really is the same as implementing the ActionListener interface in another class. It just has the advantage of being more compact.

Note: An example of the use of implementing an ActionListener by using an anonymous inner class can be found in the A Simple Calculator Handling Button Events step-by-step. The full Java code listing can be found in a Simple Calculator Example Program.
In the JavaLanguage, this is an anonymous specialization of some class or interface. Because it is anonymous and inline, it is necessarily an inner class - i.e., defined within some other class. The following is a popular use of anonymous inner classes:
 addWindowListener(
     new WindowAdapter() {
         public void windowClosing( WindowEvent e ) {
             System.exit(0);
         }
     });
This is the same as the following non-anonymous inner:
 public class WindowClosingAdapter extends WindowAdapter {
     public void windowClosing( WindowEvent e ) {
         System.exit(0);
     }
 }

 ...

AnonymousInnerClasses can also be used to create something like closures in the JavaLanguage. However they do not "close over" the lexical environment so they aren't TrueClosures?. (They can capture the value of local variables, but they do not have access to the variable binding so they can't change the original variable. Which Java makes quite clear by only allowing InnerClasses to refer to local variables that have been declared final (so no-one can change them)).
Yes. Quite true. So you put the variable in a class -- and then you can change it. ;->
 class IntHolder {
    public int i;
 }
The second example seems much clearer than the first. Naming a class makes the code more readable, even if it requires some extra keystrokes.
Another use of the anonymous inner class is as a shortcut convenience for declaring a local inner class and creating an instance of that class.
        private static LinkedList multiple (LinkedList aList, final int factor) {
            return aList.collect ( new Transform() {
                public int calculate (int n) { return n*factor; }
            });
    }
In this example, the collect() method returns a new list based upon applying a transformation to each element of an existing list. The transformation is specified by the Transform interface. The multiple() method creates an implementation of Transform and an instance in one step. Since we only need one object of this type of transform, we do not need to give the subclass a name.
Here, the syntax for instantiating the anonymous inner class is
    Transform t = new Transform () { /* implementation code */ }

I've used AnonymousInnerClasses to make VirtuallyInitializedAccessors to create inexpensive objects whose lifetimes are just long enough to render a JavaServerPage.

No comments:

Post a Comment