设计bankaccount类
时间: 2024-10-17 20:09:18 浏览: 45
设计BankAccount类是一个常见的面向对象编程任务,它通常代表银行账户的基本结构和功能。下面是一个简化的BankAccount类的设计概述:
```java
class BankAccount {
// 定义属性
private String accountNumber;
private String ownerName;
private double balance;
// 构造函数,初始化属性
public BankAccount(String accountNumber, String ownerName, double initialBalance) {
this.accountNumber = accountNumber;
this.ownerName = ownerName;
this.balance = initialBalance;
}
// 获取属性的方法
public String getAccountNumber() {
return accountNumber;
}
public String getOwnerName() {
return ownerName;
}
public double getBalance() {
return balance;
}
// 改变余额的方法
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("存款成功,当前余额为:" + balance);
} else {
System.out.println("无效操作,无法存款零或负数金额");
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("取款成功,当前余额为:" + balance);
} else {
System.out.println("无效操作,尝试取款金额超过余额或者为负数");
}
}
// 显示账户信息的方法
@Override
public String toString() {
return "账户号:" + accountNumber + ", 账户名:" + ownerName + ", 当前余额:" + balance;
}
}
```
阅读全文