Java Reference
In-Depth Information
1.12. Interfaces
Sometimes you want only to declare methods an object must support
but not to supply the implementation of those methods. As long as their
behavior meets specific criteriacalled the contract implementation details
of the methods are irrelevant. These declarations define a type, and any
class that implements those methods can be said to have that type,
regardless of how the methods are implemented. For example, to ask
whether a particular value is contained in a set of values, details of how
those values are stored are irrelevant. You want the methods to work
equally well with a linked list of values, a hashtable of values, or any oth-
er data structure.
To support this, you can define an interface. An interface is like a class
but has only empty declarations of its methods. The designer of the in-
terface declares the methods that must be supported by classes that im-
plement the interface and declares what those methods should do. Here
is a Lookup interface for finding a value in a set of values:
interface Lookup {
/** Return the value associated with the name, or
* null if there is no such value */
Object find(String name);
}
The Lookup interface declares one method, find , that takes a String and
returns the value associated with that name, or null if there is no as-
sociated value. In the interface no implementation can be given for the
methoda class that implements the interface is responsible for providing
a specific implementationso instead of a method body we simply have a
semicolon. Code that uses references of type Lookup (references to ob-
jects that implement the Lookup interface) can invoke the find method
and get the expected results, no matter what the actual type of the ob-
ject is:
 
Search WWH ::




Custom Search