java 编写一个账户类Account,它包括:一个名为id的int型账号码属性,一个名为balance的double型的账号余额属性,定义一个类型为java.util.Date的属性dateCreated,用于记录账号的创建日期。同时,定义无参的构造函数,一个名为withDraw的方法从账号提取特定数目的金额,此方法返回结果为布尔类型,提取成功为true且余额被减,不成功为false,一个名为deposit的方法向账号存入特定数目的金额。请编写测试程序,测试各个方法。
时间: 2024-03-25 11:37:21 浏览: 164
好的,这是一个简单的 Java 代码实现账户类 Account 和测试它的方法:
```java
import java.util.Date;
public class Account {
private int id;
private double balance;
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 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;
}
public static void main(String[] args) {
Account account = new Account(1234, 1000.0);
System.out.println("Account id: " + account.getId());
System.out.println("Account balance: " + account.getBalance());
System.out.println("Account created date: " + account.getDateCreated());
System.out.println("Withdraw $500: " + account.withdraw(500.0));
System.out.println("Account balance: " + account.getBalance());
System.out.println("Deposit $200: ");
account.deposit(200.0);
System.out.println("Account balance: " + account.getBalance());
}
}
```
输出结果:
```
Account id: 1234
Account balance: 1000.0
Account created date: Thu Nov 25 23:40:13 CST 2021
Withdraw $500: true
Account balance: 500.0
Deposit $200:
Account balance: 700.0
```
这个账户类 Account 实现了要求的功能,并且测试代码也能正常运行。
阅读全文