by Dinesh Thakur Category: Swing

The most common use of inner classes is with event handling. An inner class can be used to implement a particular listener interface or to subclass a particular adapter. This has the benefit of separating out the control aspect of the interface from the display elements. It also means that the event handler inner class can inherit from a different class to the encompassing class.

 

For example: Suppose you have a class that extends the Frame class. Suppose now you want to use a WindowAdapter class to handle window events. Since Java does not support multiple inheritance so your class cannot extend both the Frame and WindowAdapter class. A solution to this problem is to define an inner class i.e. a class inside the Frame subclass that extends the WindowAdapter class.

import javax.swing.*;

import java.awt.event.*;
import java.awt.*;
class NamedInnerClass  extends JFrame
{
      NamedInnerClass()
      {
        addWindowListener(new MyAdapterClass());
      }
      class MyAdapterClass extends WindowAdapter
     {
        public void windowClosing(WindowEvent e)
        {
          System.exit(0);
        }
     }
}
    class InnerEventClassJavaExample
  {
      public static void main(String args[])
      {
        NamedInnerClass frame = new NamedInnerClass();
        frame.setTitle("Named Inner Class Java Example");
        frame.setBounds(200,150,180,150);
        frame.setVisible(true);
      }
  }

Named Inner Class Java Example



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.



Related Articles