Java Reference
In-Depth Information
}
}
Listing2-43
retrofits
Listing2-33
'
sclasshierarchytotakeadvantageof
Listing2-42
'
s
Drawable
interface. You will notice that each of classes
Point
and
Circle
im-
plementsthisinterfacebyattachingthe
implements Drawable
clausetoitsclass
header.
Toimplementaninterface,theclassmustspecify,foreachinterfacemethodheader,
amethodwhoseheaderhasthesamesignatureandreturntypeasthatintheinterface's
method header, and a code body to go with the method header.
Caution
When implementing a method, do not forget that the interface's methods
areimplicitlydeclared
public
.Ifyouforgettoinclude
public
intheimplemented
method's declaration, the compiler will report an error because you are attempting to
assign weaker access to the implemented method.
Whenaclassimplementsaninterface,theclassinheritstheinterface'sconstantsand
methodheaders,andoverridesthemethodheadersbyprovidingimplementations(hence
the
@Override
annotation). This is known as
interface inheritance
.
It turns out that
Circle
's header does not need the
implements Drawable
clause.Ifthisclauseisnotpresent,
Circle
inherits
Point
's
draw()
method,andis
still considered to be a
Drawable
, whether or not it overrides this method.
An interface specifies a type whose data values are the objects whose classes im-
plement the interface, and whose behaviors are those specified by the interface. This
fact implies that you can assign an object's reference to a variable of the interface
type,providedthattheobject'sclassimplements theinterface. Thefollowingexample
provides a demonstration:
public static void main(String[] args)
{
Drawable[] drawables = new Drawable[] { new Point(10,
20),
new
Circle(10,
20, 30) };
for (int i = 0; i < drawables.length; i++)
drawables[i].draw(Drawable.RED);
}