设计一个名为Account的账户类,包括: l id私有数据域,int类型(默认值0) l balance私有数据域,double类型(默认值0) l rate私有数据域,double类型(默认值0),且所有账户利率相同 l 以上数据域的访问器与修改器 l dataCreated私有数据域,Date类型 l 日期数据域的访问器 l 无参构造方法 l 指定id和余额的构造方法 l getMonthlyInterest方法,返回月利息(余额*月利率) l withdraw方法,取款 l deposit方法,存款 设计一个名为Checking account的子类,包括: l 透支限定额,受保护的数据域 l toString方法 实现并测试:创建指定帐户名、余额,设置利率,存款、取款、打印余额、月利息以及开户日期。
时间: 2023-06-27 17:05:36 浏览: 138
Account类的代码如下:
```java
import java.util.Date;
public class Account {
private int id;
private double balance;
private double rate;
private Date dateCreated;
public Account() {
this(0, 0);
}
public Account(int id, double balance) {
this.id = id;
this.balance = balance;
this.rate = 0;
this.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 getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
public Date getDateCreated() {
return dateCreated;
}
public double getMonthlyInterest() {
return balance * rate / 12;
}
public void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
}
}
public void deposit(double amount) {
balance += amount;
}
}
```
CheckingAccount子类的代码如下:
```java
public class CheckingAccount extends Account {
protected double overdraftLimit;
public CheckingAccount(int id, double balance, double overdraftLimit) {
super(id, balance);
this.overdraftLimit = overdraftLimit;
}
public double getOverdraftLimit() {
return overdraftLimit;
}
public void setOverdraftLimit(double overdraftLimit) {
this.overdraftLimit = overdraftLimit;
}
@Override
public void withdraw(double amount) {
if (balance + overdraftLimit >= amount) {
balance -= amount;
}
}
@Override
public String toString() {
return "CheckingAccount{" +
"id=" + getId() +
", balance=" + getBalance() +
", overdraftLimit=" + overdraftLimit +
'}';
}
}
```
测试代码如下:
```java
public class Test {
public static void main(String[] args) {
CheckingAccount account = new CheckingAccount(123, 1000, 500);
account.setRate(0.01);
account.deposit(500);
account.withdraw(2000);
System.out.println(account.getBalance());
System.out.println(account.getMonthlyInterest());
System.out.println(account.getDateCreated());
System.out.println(account);
}
}
```
输出结果如下:
```
500.0
6.25
Tue Oct 26 15:58:36 CST 2021
CheckingAccount{id=123, balance=500.0, overdraftLimit=500.0}
```
阅读全文