Anonymous inner classes can also be used to provide a similar facility as that provided by inner classes.
In this approach, the event listener is implemented as an anonymous inner class. The inner class declaration is incorporated into the syntax needed to register the component with the event listener. Although anonymous inner classes result in more compact programs but they do make the code more difficult to read. For example : Suppose we want to write an anonymous WindowAdapter class that terminates the JVM when the user closes the window.
addWindowListener(new WindowAdapter()
{
public void WindowClosing(WindowEvent e)
{
System.exit(0);
}
}) ;
In this code,
• A class is defined without a name that extends the WindowAdapter class .
• A windowClosing ()method is defined in this anonymous class that exits the program when the user closes the window. The remaining six do nothing methods are inherited from the WindowAdapter class .
• An object of WindowAdapter is created without a name and passes to the addWindowListener () method.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class AnonymousInnerClasses extends JFrame
{
AnonymousInnerClasses()
{
addWindowListener(new WindowAdapter()
{
public void WindowClosing(WindowEvent e)
{
System.exit(0);
}
}) ;
}
}
class AnonymousInnerClassesJavaExample
{
public static void main(String args[])
{
AnonymousInnerClasses frame = new AnonymousInnerClasses();
frame.setTitle("Anonymous Inner Classes Java Example");
frame.setBounds(200,150,180,150);
frame.setVisible(true);
}
}