Java Reference
In-Depth Information
interface
Payable
. We then modify class
Employee
such that it also implements interface
Payable
. Finally, we update
Employee
subclass
SalariedEmployee
to “fit” into the
Pay-
able
hierarchy by renaming
SalariedEmployee
method
earnings
as
getPaymentAmount
.
Good Programming Practice 10.2
When declaring a method in an interface, choose a method name that describes the meth-
od's purpose in a
general
manner, because the method may be implemented by many
un-
related
classes.
Classes
Invoice
and
Employee
both represent things for which the company must be
able to calculate a payment amount. Both classes implement the
Payable
interface, so a
program can invoke method
getPaymentAmount
on
Invoice
objects and
Employee
objects
alike. As we'll soon see, this enables the
polymorphic
processing of
Invoice
s and
Employee
s
required for the company's accounts payable application.
The UML class diagram in Fig. 10.10 shows the interface and class hierarchy used in
our accounts payable application. The hierarchy begins with interface
Payable
. The UML
distinguishes an interface from other classes by placing the word “interface” in guillemets
(« and »
)
above the interface name. The UML expresses the relationship between a class
and an interface through a relationship known as
realization
. A class is said to
realize
, or
implement
, the methods of an interface. A class diagram models a realization as a dashed
arrow with a hollow arrowhead pointing from the implementing class to the interface. The
diagram in Fig. 10.10 indicates that classes
Invoice
and
Employee
each realize interface
Payable
. As in the class diagram of Fig. 10.2, class
Employee
appears in
italics
, indicating
that it's an
abstract class
.
Concrete
class
SalariedEmployee
extends
Employee
,
inheriting its
superclass's realization relationship
with interface
Payable
.
«interface»
Payable
Invoice
Employee
SalariedEmployee
Fig. 10.10
|
Payable
hierarchy UML class diagram.
The declaration of interface
Payable
begins in Fig. 10.11 at line 4. Interface
Payable
con-
tains
public
abstract
method
getPaymentAmount
. Interface methods are always
public
and
abstract
, so they do not need to be declared as such. Interface
Payable
has only one
method, but interfaces can have
any
number of methods. In addition, method
get-
PaymentAmount
has no parameters, but interface methods
can
have parameters. Interfaces
may also contain
final
static
constants.