Java Reference
In-Depth Information
Java syntax: Interface definition
public interface interface-name {
abstract-method definitions and
constant definitions
Java syntax: Method declaration in an interface
type method-name ( par-dec , ... , par-dec ) ;
Example : int max( int x, int y);
Note : Use void instead of a type for a procedure.
Purpose : To define an interface.
Purpose : To give (only) the header of a method, and
not its body.
the same capability of forcing a class to implement some methods, but in a dif-
ferent way.
The prefix inter means between , so the word interface means between faces .
In a dictionary, you will find a definition like: a plane or other surface forming a
common boundary of bodies or spaces. In programming, we generally think of
an interface as something that describes how two program parts interact. For
example, the interface might be a specification that describes how one of the pro-
gram parts, the server, can be used by the other part, the client.
In Java, the word interface has a more restricted meaning: an interface is a
specification of the syntax of methods that a class must implement. For example,
this interface indicates that a class must implement method actionPerformed :
/** Interface for receiving action events */
public interface ActionListener {
/** Process event e */
void actionPerformed(ActionEvent e);
Each abstract method in an interface definition is like a conventional method
except that its body has been replaced by a semicolon. It is called “abstract”
because there is no implementation, i.e. no method body.
The only modifiers allowed are public and abstract , but you are discour-
aged from using even these since they are the defaults and the only possibility.
Definitions of constants can also appear in an interface definition, but we
save their description for later.
Java will check that any class that purports to implement ActionListener
—we see what this means later— does indeed implement method actionPer-
formed . Java will not check to make sure that the implementation satisfies the
specification given by the comment on the method. Nevertheless, always place
such a comment-specification on each method that is defined in the interface so
that the reader knows what the method is supposed to do.
Implementing an interface
Below, we give a class C1 that implements interface ActionListener , as
indicated by the implements clause implements ActionListener :
Search WWH ::

Custom Search