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 associated 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 objects that implement the Lookup interface) can invoke the find method and get the expected results,
no matter what the actual type of the object is:
void processValues(String[] names, Lookup table) {
for (int i = 0; i < names.length; i++) {
Object value = table.find(names[i]);
if (value != null)
processValue(names[i], value);
}
}
A class can implement as many interfaces as you choose. This example implements Lookup using a simple
array (methods to set or remove values are left out for simplicity):
class SimpleLookup implements Lookup {
private String[] names;
private Object[] values;
public Object find(String name) {
for (int i = 0; i < names.length; i++) {
if (names[i].equals(name))
return values[i];
}
return null; // not found
}
// ...
}
An interface can also declare named constants that are static and final. Additionally, an interface can
declare other nested interfaces and even classes. These nested types are discussed in detail in Chapter 5. All
the members of an interface are implicitly, or explicitly, publicso they can be accessed anywhere the
interface itself is accessible.
Interfaces can be extended using the extends keyword. An interface can extend one or more other
interfaces, adding new constants or new methods that must be implemented by any class that implements the
extended interface.
A class's supertypes are the class it extends and the interfaces it implements, including all the supertypes of
those classes and interfaces. So an object is not only an instance of its particular class but also of any of its