by Dinesh Thakur Category: Swing

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);
      }
  }

Anonymous Inner Classes in Java with Examples



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Search Content





Popular Article