使用java语言写代码模拟atm机
时间: 2024-09-23 18:11:57 浏览: 30
在Java中,我们可以创建一个简单的ATM模拟程序来展示多态的概念。首先,我们定义一个`BankAccount`接口,然后创建两个实现了这个接口的具体类,比如`SavingsAccount`和`CheckingAccount`。接着,我们可以定义一个`ATM`类,它有一个方法列表,其中包含对银行账户通用操作(如存款、取款和查询余额)。每个具体的账户类都提供它们特定的操作。
```java
// 银行账户接口
interface BankAccount {
void deposit(double amount);
double withdraw(double amount) throws InsufficientFundsException;
double getBalance();
}
// 存款账户类
class SavingsAccount implements BankAccount {
private double balance;
@Override
public void deposit(double amount) {
balance += amount;
}
@Override
public double withdraw(double amount) throws InsufficientFundsException {
if (amount <= balance) {
balance -= amount;
return amount;
} else {
throw new InsufficientFundsException("Insufficient funds");
}
}
@Override
public double getBalance() {
return balance;
}
}
// 普通检查账户类
class CheckingAccount extends SavingsAccount {
// 检查账户可能有不同的费用处理逻辑
@Override
public double withdraw(double amount) throws InsufficientFundsException {
double withdrawal = super.withdraw(amount - 0.5); // 每次取款扣除0.5元手续费
System.out.println("Transaction fee: $0.50");
return withdrawal;
}
}
// ATM类
class ATM {
public void performOperation(BankAccount account, String operation, double amount) {
switch (operation.toLowerCase()) {
case "deposit":
account.deposit(amount);
break;
case "withdraw":
try {
double withdrawn = account.withdraw(amount);
System.out.printf("Withdrawal successful! Amount withdrawn: %.2f\n", withdrawn);
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage());
}
break;
case "balance":
System.out.printf("Current balance: %.2f\n", account.getBalance());
break;
default:
System.out.println("Invalid operation.");
}
}
}
public class Main {
public static void main(String[] args) {
ATM atm = new ATM();
atm.performOperation(new SavingsAccount(), "Deposit", 1000);
atm.performOperation(new CheckingAccount(), "Withdraw", 800);
}
}
```
阅读全文