Implementing an Interface – Nested Type Declarations

Implementing an Interface

The following syntax can be used for defining and instantiating an anonymous class that implements an interface specified by the interface name:

Click here to view code image

new
interface_name
<
optional_parameterized_types
>() {
member_declarations
 }

An anonymous class provides a single interface implementation. No arguments are passed, as an interface does not define a constructor. The anonymous class implicitly extends the Object class. Note that no implements clause is used in the construct. The class body must provide implementation for all abstract methods declared in the interface.

An anonymous class implementing an interface is shown below. Details can be found in Example 9.14. The static method createIDrawable() at (7) defines a static anonymous class at (8), which implements the interface IDrawable, by providing an implementation of the method draw(). The functionality of objects of an anonymous class that implements an interface is available through references of the interface type and the Object type—that is, its supertypes.

Click here to view code image

interface IDrawable {                          // (1) Interface
  void draw();
}
// …
class Painter {                                // (3) Top-level Class
  // …
  public static IDrawable createIDrawable() {  // (7) Static Method
    return new IDrawable() {                   // (8) Implements interface at (1)
      @Override public void draw() {
        System.out.println(“Drawing a new IDrawable.”);
      }
};
  }
}
// …

The following code is an example of a typical use of anonymous classes in building GUI applications. The anonymous class at (1) implements the java.awt.event.-ActionListener interface that has the method actionPerformed(). When the addActionListener() method is called on the GUI button denoted by the reference quitButton, the anonymous class is instantiated and the reference value of the object is passed as a parameter to the method. The method addActionListener() of the GUI button registers the reference value, and when the user clicks the GUI button, it can invoke the actionPerformed() method on the ActionListener object.

Click here to view code image

quitButton.addActionListener(
    new ActionListener() {    // (1) Anonymous class implements an interface
      // Invoked when the user clicks the quit button.
      @Override public void actionPerformed(ActionEvent evt) {
        System.exit(0);       // (2) Terminates the program
      }
    }
);

Leave a Reply

Your email address will not be published. Required fields are marked *