(賬戶類 Account)設計一個名為 Account 的類,它包括:
- 一個名為 id 的 int 類型私有資料域(預設值為 0)。
- 一個名為 balance 的 double 類型私有資料域(預設值為 0)。
- 一個名為 annualInterestRate 的 double 類型私有資料域存儲目前利率(預設值為 0)。假設所有的賬戶都有相同的利率。
- 一個名為 dateCreated 的 Date 類型的私有資料域,存儲賬戶的開戶日期。
- 一個用于建立預設賬戶的無參構造方法。
- 一個用于建立帶特定 id 和初始餘額的賬戶的構造方法。
- id、balance 和 annualIntersRate 的通路器和修改器。
- dateCreated 的通路器。
- 一個名為 getMonthlyInterestRate() 的方法,傳回月利率。
- 一個名為 withDraw 的方法,從賬戶提取特定數額。
-
一個名為 deposit 的方法向賬戶存儲特定數額。
畫出該類的 UML 圖并實作這個類。
提示:方法 getMonthlyInterest() 用于傳回月利息,而不是利息。月利息是 balance * monthlyInterestRate。monthlyInterestRate 是 annualInterestRate / 12。注意,annualInterestRate 是一個百分數,比如 4.5%。你需要将其除以 100。
編寫一個測試程式,建立一個賬戶 ID 為 1122、餘額為 20 000 美元、年利率為 4.5% 的 Account 對象。使用 withDraw 方法取款 2500 美元,使用 deposit 方法存款 3000 美元,然後列印餘額、月利息以及這個賬戶的開戶日期。
import java.util.Date;
public class Practice_9_7 {
public static void main(String[] args) {
Account account = new Account(1122, 20000);
account.setAnnualInterestRate(4.5);
account.withDraw(2500);
account.deposit(3000);
System.out.println("Balance: " + account.getBalance() + "\n"
+ "Monthly Interest Rate: " + account.getMonthlyInterestRate() + "\n"
+ "Date Created: " + account.getDateCreated());
}
}
class Account {
private int id = 0;
private double balance = 0;
private static double annualInterestRate = 0;
private Date dateCreated;
public Account() {
dateCreated = new Date();
}
public Account(int id, double balance) {
this.id = id;
this.balance = balance;
dateCreated = new Date();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public Date getDateCreated() {
return dateCreated;
}
public double getMonthlyInterestRate() {
double monthlyInterestRate = annualInterestRate / 12;
return balance * monthlyInterestRate / 100;
}
public void withDraw(double money) {
balance -= money;
}
public void deposit(double money) {
balance += money;
}
}
輸出結果為:
Balance: 20500.0
Monthly Interest Rate: 76.875
Date Created: Sat Mar 04 12:37:56 CST 2017