Java Reference
In-Depth Information
In Chapter 10, Object-Oriented Programming: Polymorphism and Interfaces, we
present a more elegant way to implement
switch
logic—we use a technique called
poly-
morphism
to create programs that are often clearer, easier to maintain and easier to extend
than programs using
switch
logic.
Statements
String
s can be used as controlling expressions in
switch
statements, and
String
literals
can be used in
case
labels. To demonstrate that
String
s can be used as controlling expres-
sions in
switch
statements and that
String
literals can be used in
case
labels, we'll imple-
ment an app that meets the following requirements:
You've been hired by an auto insurance company that serves these northeast states—
Connecticut, Maine, Massachusetts, New Hampshire, New Jersey, New York, Pennsyl-
vania, Rhode Island and Vermont. The company would like you to create a program
that produces a report indicating for each of their auto insurance policies whether the
policy is held in a state with “no-fault” auto insurance—Massachusetts, New Jersey,
New York and Pennsylvania.
The Java app that meets these requirements contains two classes—
AutoPolicy
(Fig. 5.11)
and
AutoPolicyTest
(Fig. 5.12).
Class
AutoPolicy
Class
AutoPolicy
(Fig. 5.11) represents an auto insurance policy. The class contains:
•
int
instance variable
accountNumber
(line 5) to store the policy's account number
•
String
instance variable
makeAndModel
(line 6) to store the car's make and model
(such as a
"Toyota
Camry"
)
•
String
instance variable
state
(line 7) to store a two-character state abbreviation
representing the state in which the policy is held (e.g.,
"MA"
for Massachusetts)
• a constructor (lines 10-15) that initializes the class's instance variables
•m t s
setAccountNumber
and
getAccountNumber
(lines 18-27) to
set
and
get
an
AutoPolicy
's
accountNumber
instance variable
•m t s
setMakeAndModel
and
getMakeAndModel
(lines 30-39) to
set
and
get
an
AutoPolicy
's
makeAndModel
instance variable
•m t s
setState
and
getState
(lines 42-51) to
set
and
get
an
AutoPolicy
's
state
instance variable
•m t d
isNoFaultState
(lines 54-70) to return a
boolean
value indicating
whether the policy is held in a no-fault auto insurance state; note the method
name—the naming convention for a
get
method that returns a
boolean
value is
to begin the name with
"is"
rather than
"get"
(such a method is commonly
called a
predicate method
).
In method
isNoFaultState
, the
switch
statement's controlling expression (line 59) is the
String
returned by
AutoPolicy
method
getState
. The
switch
statement compares the
controlling expression's value with the
case
labels (line 61) to determine whether the pol-
icy is held in Massachusetts, New Jersey, New York or Pennsylvania (the no-fault states).