设计一个bank类实现银行某账户的资金往来账目管理
时间: 2024-10-19 09:16:44 浏览: 44
设计一个Bank类来实现银行账户资金往来的账目管理,通常需要包含以下几个核心部分:
1. **账户类(Account)**: 每个账户都有一个唯一的标识(如账号ID),存储余额(balance)。账户类应提供基本操作方法,如存款(deposit), 取款(withdrawal)以及查询余额(balance_check)。
```java
public class Account {
private String accountNumber;
private double balance;
public Account(String accountNumber) {
this.accountNumber = accountNumber;
this.balance = 0.0;
}
// 存款方法
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
// 取款方法
public boolean withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
return true;
} else {
return false; // 资金不足
}
}
// 查询余额
public double getBalance() {
return balance;
}
}
```
2. **Bank类(Bank)**: 银行类管理一整套账户,并可能有账户列表或哈希表来快速查找账户。Bank类可以提供添加新账户(addAccount),删除账户(removeAccount),以及处理转账(transactBetweenAccounts)等服务。
```java
import java.util.HashMap;
public class Bank {
private HashMap<String, Account> accounts;
public Bank() {
accounts = new HashMap<>();
}
// 添加账户
public void addAccount(Account account) {
accounts.put(account.getAccountNumber(), account);
}
// 删除账户
public void removeAccount(String accountNumber) {
accounts.remove(accountNumber);
}
// 转账方法
public boolean transfer(String fromAccount, String toAccount, double amount) {
Account from = accounts.get(fromAccount);
Account to = accounts.get(toAccount);
if (from != null && to != null && from.withdraw(amount)) {
to.deposit(amount);
return true;
} else {
return false; // 账户不存在或资金不足
}
}
}
// 示例使用
public static void main(String[] args) {
Bank bank = new Bank();
Account account1 = new Account("123456");
Account account2 = new Account("789012");
bank.addAccount(account1);
bank.addAccount(account2);
// 转账示例
boolean result = bank.transfer("123456", "789012", 500.0);
System.out.println(result ? "转账成功" : "转账失败");
}
```
阅读全文