Saturday, June 9, 2007

Anonymous Inner Classes in Java

Anonymous Inner Classes are mainly used for using the method of a class without creating class or class objects. These classes don't have any name also. These classes are mostly used in event handling. A small code is given below to show how the anonymous classes are used.

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JFrame;

public class WindowAdapterTest {
public static void main(String args[]) {
JFrame frame = new JFrame("Window Listener");
WindowListener listener = new WindowAdapter() { // anonymous class starts here
public void windowClosing(WindowEvent w) {
System.exit(0);
}
}; //anonymous class ends here
frame.addWindowListener(listener);
frame.setSize(300, 300);
frame.show();
}
}

No comments: