面向对象在atm中实现转账
时间: 2024-10-29 10:20:44 浏览: 19
.Net用面向对象实现ATM机
4星 · 用户满意度95%
在ATM(自动取款机)系统中,面向对象编程可以有效地实现转账功能。我们可以创建以下几个核心的类:
1. **账户类(Account)**: 它代表用户的银行账户,包含属性如账号、余额等,并提供转账方法(transfer)。
```java
public class Account {
private String accountNumber;
private double balance;
public Account(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
// 转账方法
public boolean transfer(Account receiverAccount, double amount) {
if (amount > balance || receiverAccount == null) {
return false; // 资金不足或接收方无效
}
this.balance -= amount;
receiverAccount.balance += amount;
return true;
}
}
```
2. **用户类(User)**: 用户持有其名下的账户,并可能有姓名和其他个人信息。
```java
public class User {
private String name;
private Account account;
public User(String name, Account account) {
this.name = name;
this.account = account;
}
public void atmTransfer(Account targetAccount, double amount) {
account.transfer(targetAccount, amount);
}
}
```
3. **ATM类(ATMMachine)**: 提供用户交互界面,处理用户操作并调用账户转账方法。
```java
public class ATMMachine {
public void deposit(User user, double amount) {
user.account.deposit(amount); // 存款
}
public void withdraw(User user, double amount) {
if (user.account.withdraw(amount)) { // 提款
System.out.println("Withdrawal successful.");
} else {
System.out.println("Insufficient funds.");
}
}
public void transfer(User sender, User receiver, double amount) {
if (sender.atmTransfer(receiver.account, amount)) {
System.out.println("Transfer successful.");
} else {
System.out.println("Transfer failed.");
}
}
}
```
通过这种方式,无论是普通用户还是管理员,都可以通过调用ATM的相应方法来进行转账操作,体现了面向对象的封装、继承和多态特性。
阅读全文