Java Reference
In-Depth Information
To implement an interface, a class must provide bodies (implementations) for the meth-
ods described by the interface. Each class is free to determine the details of its own im-
plementation. Two classes might implement the same interface in different ways, but each
class still supports the same set of methods. Thus, code that has knowledge of the interface
can use objects of either class since the interface to those objects is the same. By providing
the
interface
keyword, Java allows you to fully utilize the “one interface, multiple meth-
ods” aspect of polymorphism.
Before continuing an important point needs to be made. JDK 8 added a feature to
inter-
face
that makes a significant change to its capabilities. Prior to JDK 8, an interface could
not define any implementation whatsoever. Thus, prior to JDK 8, an interface could define
only what, but not how, as just described. JDK 8 changes this. Today, it is possible to add
a
default implementation
to an interface method. Thus, it is now possible for
interface
to
specify some behavior. However, default methods constitute what is, in essence, a special-
use feature, and the original intent behind
interface
still remains. Therefore, as a general
rule, you will still often create and use interfaces in which no default methods exist. For
this reason, we will begin by discussing the interface in its traditional form. The default
method is described at the end of this chapter.
Here is a simplified general form of a traditional interface:
Here,
access
is either
public
or not used. When no access modifier is included, then default
access results, and the interface is available only to other members of its package. When it
is declared as
public
, the interface can be used by any other code. (When an
interface
is
declared
public
, it must be in a file of the same name.)
name
is the name of the interface
and can be any valid identifier.
In the traditional form of an interface, methods are declared using only their return type
and signature. They are, essentially, abstract methods. Thus, each class that includes such