Java Reference
In-Depth Information
Interfaces
In
Chapter 3
, we met the idea of inheritance. We also saw that a Java class can only
inherit from a single class. This is quite a big restriction on the kinds of object-
oriented programs that we want to make. The designers of Java knew this, but they
also wanted to ensure that Java's approach to object-oriented programming was less
complex than, for example, that of C++.
The solution that they chose was to create the concept of an interface. Like a class,
an
interface
defines a new reference type. As its name implies, an interface is
intended to represent only an API—so it provides a description of a type, and the
methods (and signatures) that classes that
implement
that API should provide.
In general, a Java interface does not provide any implementation code for the meth‐
ods that it describes. These methods are considered
mandatory
—any class that
wishes to implement the interface must provide an implementation of these
methods.
However, an interface may wish to mark that some API methods are optional, and
that implementing classes do not need to implement them if they choose not to.
This is done with the
default
keyword—and the interface must provide a
default
implementation of these optional methods, which will be used by any implementa‐
tion that elects not to implement them.
The ability to have optional methods in interfaces is new in
Java 8. It is not available in any earlier version. See
“Default
Methods” on page 140
for a full description of how optional
(also called default) methods work.
It is not possible to directly instantiate an interface and create a member of the
interface type. Instead, a class must
implement
the interface to provide the necessary
method bodies.
Any instances of that class are members of both the type defined by the class and
the type defined by the interface. Objects that do not share the same class or super‐
class may still be members of the same type by virtue of implementing the same
interface.
Deining an Interface
An interface definition is much like a class definition in which all the (nondefault)
methods are abstract and the keyword
class
has been replaced with
interface
. For
example, the following code shows the definition of an interface named
Centered
. A
Shape
class, such as those defined in
Chapter 3
, might implement this interface if it
wants to allow the coordinates of its center to be set and queried:
interface
Centered
{
void
setCenter
(
double
x
,
double
y
);