Java Reference
In-Depth Information
an
interface
must implement all of its methods. In an interface, methods are implicitly
public
.
Variables declared in an
interface
are not instance variables. Instead, they are implicitly
public
,
final
, and
static
and must be initialized. Thus, they are essentially constants. Here
is an example of an
interface
definition. It specifies the interface to a class that generates a
series of numbers.
This interface is declared
public
so that it can be implemented by code in any package.
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 required by the interface. The general form of a class that includes the
imple-
ments
clause looks like this:
To implement more than one interface, the interfaces are separated with a comma. Of
course, the
extends
clause is optional.
The methods that implement an interface must be declared
public
. Also, the type sig-
nature of the implementing method must match exactly the type signature specified in the
interface
definition.
Here is an example that implements the
Series
interface shown earlier. It creates a class
called
ByTwos
, which generates a series of numbers, each two greater than the previous
one.