You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
64 lines
2.2 KiB
64 lines
2.2 KiB
package w3;
|
|
|
|
public class BankAccount {
|
|
// 1. 私有属性(封装)
|
|
private final String accountNumber; // 账户号(final 修饰,创建后不可修改)
|
|
private String ownerName; // 户主姓名(可修改)
|
|
private double balance; // 余额(只能通过存取款修改)
|
|
|
|
// 2. 构造方法(创建账户必须提供账户号和户主姓名,初始余额为0)
|
|
public BankAccount(String accountNumber, String ownerName) {
|
|
this.accountNumber = accountNumber;
|
|
this.ownerName = ownerName;
|
|
this.balance = 0.0; // 初始余额为0
|
|
}
|
|
|
|
// 3. Getter 方法(对外提供查询)
|
|
public String getAccountNumber() {
|
|
return accountNumber;
|
|
}
|
|
|
|
public String getOwnerName() {
|
|
return ownerName;
|
|
}
|
|
|
|
public double getBalance() {
|
|
return balance;
|
|
}
|
|
|
|
// 4. Setter 方法(仅允许修改户主姓名)
|
|
public void setOwnerName(String ownerName) {
|
|
this.ownerName = ownerName;
|
|
}
|
|
|
|
// 5. 存款操作(金额必须>0)
|
|
public void deposit(double amount) {
|
|
if (amount > 0) {
|
|
this.balance += amount;
|
|
System.out.println("存款成功!当前余额:" + this.balance);
|
|
} else {
|
|
System.out.println("存款失败:存款金额必须大于0!");
|
|
}
|
|
}
|
|
|
|
// 6. 取款操作(金额必须>0且不超过当前余额)
|
|
public void withdraw(double amount) {
|
|
if (amount > 0 && amount <= this.balance) {
|
|
this.balance -= amount;
|
|
System.out.println("取款成功!当前余额:" + this.balance);
|
|
} else if (amount <= 0) {
|
|
System.out.println("取款失败:取款金额必须大于0!");
|
|
} else {
|
|
System.out.println("取款失败:余额不足!");
|
|
}
|
|
}
|
|
|
|
// 7. 打印账户信息(方便测试)
|
|
public void printAccountInfo() {
|
|
System.out.println("===== 账户信息 =====");
|
|
System.out.println("账户号:" + accountNumber);
|
|
System.out.println("户主姓名:" + ownerName);
|
|
System.out.println("当前余额:" + balance);
|
|
System.out.println("====================");
|
|
}
|
|
}
|