Java Reference
In-Depth Information
43
return
name;
// give value of name back to caller
44
}
// end method getName
45
}
// end class Account
Fig. 3.8
|
Account
class with a
double
instance variable
balance
and a constructor and
deposit
method that perform validation. (Part 2 of 2.)
Account
Class Two-Parameter Constructor
The class has a
constructor
and four
methods
. It's common for someone opening an account
to deposit money immediately, so the constructor (lines 11-19) now receives a second pa-
rameter—
initialBalance
of type
double
that represents the
starting balance
. Lines 17-18
ensure that
initialBalance
is greater than
0.0
. If so,
initialBalance
's value is assigned to
instance variable
balance
. Otherwise,
balance
remains at
0.0
—its
default initial value
.
Account
Class
deposit
Method
Method
deposit
(lines 22-26) does
not
return any data when it completes its task, so its
return type is
void
. The method receives one parameter named
depositAmount
—a
dou-
ble
value that's
added
to the
balance
only
if the parameter value is
valid
(i.e., greater than
zero). Line 25 first adds the current
balance
and
depositAmount
, forming a
temporary
sum which is
then
assigned to
balance
,
replacing
its prior value (recall that addition has a
higher
precedence than assignment). It's important to understand that the calculation on
the right side of the assignment operator in line 25 does
not
modify the balance—that's
why the assignment is necessary.
Account
Class
getBalance
Method
Method
getBalance
(lines 29-32) allows
clients
of the class (i.e., other classes whose meth-
ods call the methods of this class) to obtain the value of a particular
Account
object's
bal-
ance
. The method specifies return type
double
and an
empty
parameter list.
Account
's Methods Can All Use
balance
Once again, the statements in lines 18, 25 and 31 use the variable
balance
even though it
was
not
declared in
any
of the methods. We can use
balance
in these methods because it's
an
instance variable
of the class.
Class
AccountTest
(Fig. 3.9) creates two
Account
objects (lines 9-10) and initializes them
with a
valid
balance of
50.00
and an
invalid
balance of
-7.53
, respectively—for the pur-
pose of our examples, we assume that balances must be greater than or equal to zero. The
calls to method
System.out.printf
in lines 13-16 output the account names and bal-
ances, which are obtained by calling each
Account
's
getName
and
getBalance
methods.
1
// Fig. 3.9: AccountTest.java
2
// Inputting and outputting floating-point numbers with Account objects.
3
import
java.util.Scanner;
Fig. 3.9
|
Inputting and outputting floating-point numbers with
Account
objects. (Part 1 of 3.)