Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Intermediate
Oct 30, 1998



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Anonymous vs. Regular Inner Classes

Inner classes are useful for instantiating and registering listeners on event sources. When should you use an anonymous inner class and when should you use a regular inner class? If you need only one listener of a given type to be registered on a single source, you should use the anonymous form. However, if you need to register listeners of a given type on multiple sources, using the anonymous form requires you to duplicate code. You must provide code to define and register the listener on each source. Also, every listener will be a different object whether that is what you want or not.

In the case of multiple sources, using a regular (inner) listener class usually eliminates duplicate code. Also, you can register different listener objects on each source, or you can share a single listener object among multiple sources. This program uses the anonymous form to register a window listener on the JFrame object, and uses the regular form to instantiate a single listener object and register it on ten separate buttons:

import java.awt.*;
import java.awt.event.*;
import com.sun.java.swing.*;

public class InnerClasses02 extends JFrame {

public static void main(String args[]) {
	new InnerClasses02();
}//end main()
InnerClasses02() {//constructor
	JButton theButtons[] = new JButton[10];
	RegInnerClass actionListener = new RegInnerClass();
	for(int cnt = 0; cnt < 10; cnt++){
		theButtons[cnt] = new JButton("" + cnt);
	}//end for loop

	setTitle("Inner Classes");
	getContentPane().setLayout(new FlowLayout());
	// Anonymous inner class to terminate the
	// program when the JFrame is closed.
	addWindowListener(new WindowAdapter() {
		public void windowClosing(WindowEvent e) {
}//end constructor
//Regular inner class ActionListener for buttons
class RegInnerClass implements ActionListener{
	public void actionPerformed(ActionEvent e){
	}//end actionPerformed()
}//end RegInnerClass
}//end class InnerClasses02
Richard G.
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date