Java Reference
In-Depth Information
Line 33 prompts the user to enter a deposit amount for
account2
. Line 34 obtains the
input from the user by calling
Scanner
object
input
's
nextDouble
method. Lines 35-36
display the
depositAmount
. Line 37 calls object
account2
's
deposit
method with
depositAmount
as the method's
argument
; then method
deposit
adds that value to the
balance
. Finally, lines 40-43 output the
name
s and
balance
s of both
Account
s
again
to
show that
only
account2
's
balance
has changed.
Duplicated Code in Method
main
The six statements at lines 13-14, 15-16, 28-29, 30-31, 40-41 and 42-43 are almost
identical
—they each output an
Account
's
name
and
balance
. They differ only in the name
of the
Account
object—
account1
or
account2
. Duplicate code like this can create
code
maintenance problems
when that code needs to be updated—if
six
copies of the same code
all have the same error or update to be made, you must make that change
six
times,
without
making errors
. Exercise 3.15 asks you to modify Fig. 3.9 to include a
displayAccount
method that takes as a parameter an
Account
object and outputs the object's
name
and
balance
. You'll then replace
main
's duplicated statements with six calls to
displayAc-
count
, thus reducing the size of your program and improving its maintainability by having
one
copy of the code that displays an
Account
's
name
and
balance
.
Software Engineering Observation 3.4
Replacing duplicated code with calls to a method that contains one copy of that code can
reduce the size of your program and improve its maintainability.
UML Class Diagram for Class
Account
The UML class diagram in Fig. 3.10 concisely models class
Account
of Fig. 3.8. The dia-
gram models in its
second
compartment the
private
attributes
name
of type
String
and
balance
of type
double
.
Account
- name : String
- balance : double
«constructor» Account(name : String, balance: double)
+ deposit(depositAmount : double)
+ getBalance() : double
+ setName(name : String)
+ getName() : String
Fig. 3.10
|
UML class diagram for
Account
class of Fig. 3.8.
Class
Account
's
constructor
is modeled in the
third
compartment with parameters
name
of type
String
and
initialBalance
of type
double
. The class's four
public
methods also
are modeled in the
third
compartment—operation
deposit
with a
depositAmount
param-
eter of type
double
, operation
getBalance
with a return type of
double
, operation
set-
Name
with a
name
parameter of type
String
and operation
getName
with a return type of
String
.