Java Reference
In-Depth Information
Anonymous Inner Classes and Interfaces
An anonymous inner class must either extend an existing class or implement an
existing interface. When implementing an interface, the syntax almost looks like you are
attempting to instantiate an interface, which of course would not be valid. For example,
the following anonymous inner class implements the java.awt.event.ActionListener
interface:
ActionListener x = new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(“Action occurred”);
}
};
The above inner class declaration is valid because we are not instantiating a new
ActionListener interface (which wouldn't be valid), but instead we are instantiating an
anonymous class that implements ActionListener .
Because anonymous inner classes are also local inner classes, all the same rules apply
to both. The difference with anonymous inner classes is that you can create multiple
instances of a local inner class within the method, but an anonymous inner class can only
be instantiated one time.
Inner Classes as Event Handlers
Inner classes were introduced to the Java language in JDK 1.1, which coincided with the
Java language introducing the delegation model for event handling. In the real world, an
inner class is an easy option for handling simple events.
To demonstrate, the following SimpleWindow class defi nes two inner classes: an
anonymous WindowAdapter that terminates the JVM when a user closes the window, and
an ActionListener that changes the background color of the window to red:
import java.awt.*;
import java.awt.event.*;
public class SimpleWindow {
private Frame frame;
public SimpleWindow() {
frame = new Frame(“Click the button”);
Search WWH ::




Custom Search