Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

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);
		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 buttons
class RegInnerClass implements ActionListener{
	public void actionPerformed(ActionEvent e){
		System.out.println(e.getSource());
	}//end actionPerformed()
}//end RegInnerClass
    
}//end class InnerClasses02
Richard G.
 
Comment and Contribute

 

 

 

 

 


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

 

 

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