Java Interfaces

Definition:

A Java interface is a named collection of method definitions (without implementations) and constant declarations.

A Java interface defines a set of methods, but does not implement them. A class that implements the interface must implement all of the methods defined in the interface, thereby agreeing to a certain behavior.

A Java interface allows unrelated objects to interact with one another. Java interfaces are probably most analogous to protocols (an agreed-upon behavior).

Example Interface

java.awt.event.ActionListener

The listener interface for receiving action events.

The class that is interested in processing an action event implements this interface, and the object created with that class is registered with a component (such as a button), using the component's addActionListener method. When the action event occurs, that object's actionPerformed method is invoked.

public interface ActionListener extends EventListener {

    /**
     * Invoked when an action occurs.
     */
    public void actionPerformed(ActionEvent e);

}

java.util.EventListener

A tagging interface that all event listener interfaces must extend.

public interface EventListener {
}

Example Implementation

public class Game extends JApplet implements ActionListener {
          .  .  .
   public void actionPerformed( ActionEvent e )
   {
           . . . // Carry out desired action
   }
} 

Reference


Maintained by John Loomis, last updated 1 June 2000