![]() |
![]() |
|
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
Reading: §3.2, 3.3, 3.4 .
We will work through the book's BankAccount example: expanding our file of method-stubs by declaring fields, and filling in the stubs. (Here is the stubbed-out version, and the tester class.)
Declaring a field:
class BankAccount {
double balance;
// other method (stubs) here…
}
|
Minor note: Put the adjective “private” in front of every field declaration.
class BankAccount {
private double balance;
public BankAccount() {
}
// other method (stubs)…
}
|
We know that with local variables, we should initialize them immediately after declaring them. Unfortunately, this doesn't work with fields (!). Instead, we must initialize them inside the constructor.
class BankAccount {
private double balance;
public BankAccount() {
this.balance = 0.0;
}
public BankAccount( double amt ) {
this.balance = amt;
}
// other method (stubs) here…
}
|
To make a deposit, our first version has a local variable:
public void deposit( double amt ) {
double updatedBalance = this.balance + amt;
this.balance = updatedBalance;
}
|
We can simplify the above code to get rid of the local variable (although we still need the parameter):
public void deposit( double amt ) {
this.balance = this.balance + amt;
}
|
Here is the completed code, which now passes all of our same old test cases.
1Also: For local variables, we saw that we could declare them on one line and initialize them on the next, or we could combine those two into a single line. However, for fields, you can't initialize them on the next line: you can either declare them and initialize them immediately, or initialize them inside the constructor. ↩
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
| ©2009, Ian Barland, Radford University Last modified 2009.Feb.11 (Wed) |
Please mail any suggestions (incl. typos, broken links) to ibarland |
![]() |