Definition:
An anonymous inner class is really a inner class with no name. They can be used when you only want to make one instance of the class. The use of an anonymous inner class can be a compact way of implementing an event listener:
JButton equalsButton = new JButton("=");equalsButton.setActionCommand("=");equalsButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent event){//the code here is executed when the button is clicked.}});
In the above code a
JButton
is created and instead of assigning a class which implements the ActionListener
interface using the addActionListener
method we instead write the class itself. The class has no need of a name as it only gets called in the one place. The code for the button click is placed in the actionPerformed
method which has the advantage of making it more maintainable because of it's right next to where the button is declared.Although the syntax might look a llittle more complicated it really is the same as implementing the
ActionListener
interface in another class. It just has the advantage of being more compact.Note: An example of the use of implementing an
ActionListener
by using an anonymous inner class can be found in the A Simple Calculator Handling Button Events step-by-step. The full Java code listing can be found in a Simple Calculator Example Program.
Glossary:
#ABCDEFGHIJKLMNOPQRSTUVWXYZ