Anonymous vs. Regular Inner Classes

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*;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);		theButtons[cnt].addActionListener(actionListener);		getContentPane().add(theButtons[cnt]);	}//end for loop	setTitle("Inner Classes");	getContentPane().setLayout(new FlowLayout());	setSize(300,100);	setVisible(true);    	// Anonymous inner class to terminate the	// program when the JFrame is closed.	addWindowListener(new WindowAdapter() {		public void windowClosing(WindowEvent e) {			System.exit(0);}});//end WindowListener}//end constructor//=====================================================//  //Regular inner class ActionListener for buttonsclass RegInnerClass implements ActionListener{	public void actionPerformed(ActionEvent e){		System.out.println(e.getSource());	}//end actionPerformed()}//end RegInnerClass    }//end class InnerClasses02

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist