Java编写一个账户类Account,它包括:一个名为id的int型账号码属性,一个名为balance的double型的账号余额属性,定义一个类型为java.util.Date的属性dateCreated,用于记录账号的创建日期。同时,定义无参的构造函数,一个名为withDraw的方法从账号提取特定数目的金额,此方法返回结果为布尔类型,提取成功为true且余额被减,不成功为false,一个名为deposit的方法向账号存入特定数目的金额。请编写测试程序,测试各个方法
时间: 2023-12-21 14:05:35 浏览: 171
下面是Java代码实现:
```java
import java.util.Date;
public class Account {
private int id;
private double balance;
private Date dateCreated;
public Account() {
id = 0;
balance = 0.0;
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 Date getDateCreated() {
return dateCreated;
}
public boolean withDraw(double amount) {
if (balance >= amount) {
balance -= amount;
return true;
} else {
return false;
}
}
public void deposit(double amount) {
balance += amount;
}
}
```
下面是测试程序:
```java
public class AccountTest {
public static void main(String[] args) {
Account account = new Account(123456, 1000.0);
System.out.println("账户 ID:" + account.getId());
System.out.println("账户余额:" + account.getBalance());
System.out.println("账户创建日期:" + account.getDateCreated());
System.out.println();
// 提取 500 元
if (account.withDraw(500.0)) {
System.out.println("提取成功,账户余额:" + account.getBalance());
} else {
System.out.println("提取失败,账户余额:" + account.getBalance());
}
// 存入 1000 元
account.deposit(1000.0);
System.out.println("存入 1000 元,账户余额:" + account.getBalance());
}
}
```
输出结果:
```
账户 ID:123456
账户余额:1000.0
账户创建日期:Mon Jul 26 14:14:17 CST 2021
提取成功,账户余额:500.0
存入 1000 元,账户余额:1500.0
```
阅读全文