img
Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface. To
implement an interface, include the implements clause in a class definition, and then create
the methods defined by the interface. The general form of a class that includes the implements
clause looks like this:
class classname [extends superclass] [implements interface [,interface...]] {
// class-body
}
If a class implements more than one interface, the interfaces are separated with a comma. If
a class implements two interfaces that declare the same method, then the same method will
be used by clients of either interface. The methods that implement an interface must be
declared public. Also, the type signature of the implementing method must match exactly
the type signature specified in the interface definition.
Here is a small example class that implements the Callback interface shown earlier.
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
}
Notice that callback( ) is declared using the public access specifier.
REMEMBER  When you implement an interface method, it must be declared as public.
EMEMBER
It is both permissible and common for classes that implement interfaces to define
additional members of their own. For example, the following version of Client implements
callback( ) and adds the method nonIfaceMeth( ):
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
void nonIfaceMeth() {
System.out.println("Classes that implement interfaces " +
"may also define other members, too.");
}
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home