Java Reference
In-Depth Information
constants from their defining class with the
import static
declaration. See
“Pack‐
ages and the Java Namespace” on page 88
for details.
Interfaces Versus Abstract Classes
The advent of Java 8 has fundamentally changed Java's object-oriented program‐
ming model. Before Java 8, interfaces were pure API specification and contained no
implementation. This could often lead to duplication of code if the interface had
many implementations.
In response, a coding pattern developed. This pattern takes advantage of the fact
that an abstract class does not need to be entirely abstract; it can contain a partial
implementation that subclasses can take advantage of. In some cases, numerous
subclasses can rely on method implementations provided by an abstract superclass.
The pattern consists of an interface that contains the API spec for the basic meth‐
ods, paired with a primary implementation as an abstract class. A good example
would be
java.util.List
, which is paired with
java.util.AbstractList
. Two of
the main implementations of
List
that ship with the JDK (
ArrayList
and
Linked
List
) are subclasses of
AbstractList
. As another example:
// Here is a basic interface. It represents a shape that fits inside
// of a rectangular bounding box. Any class that wants to serve as a
// RectangularShape can implement these methods from scratch.
public
interface
RectangularShape
{
void
setSize
(
double
width
,
double
height
);
void
setPosition
(
double
x
,
double
y
);
void
translate
(
double
dx
,
double
dy
);
double
area
();
boolean
isInside
();
}
// Here is a partial implementation of that interface. Many
// implementations may find this a useful starting point.
public
abstract
class
AbstractRectangularShape
implements
RectangularShape
{
// The position and size of the shape
protected
double
x
,
y
,
w
,
h
;
// Default implementations of some of the interface methods
public
void
setSize
(
double
width
,
double
height
)
{
w
=
width
;
h
=
height
;
}
public
void
setPosition
(
double
x
,
double
y
)
{
this
.
x
=
x
;
this
.
y
=
y
;
}
public
void
translate
(
double
dx
,
double
dy
)
{
x
+=
dx
;
y
+=
dy
;
}
}
The arrival of default methods in Java 8 changes this picture considerably. Interfaces
can now contain implementation code, as we saw in
“Default Methods” on page 140
.