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.

76 lines
2.5 KiB

package java01;
public class BankAccount {
// 1. 私有成员变量(封装核心)
private String accountNumber; // 账号(不可修改)
private String ownerName; // 户主姓名(可修改)
private double balance; // 余额(只能通过存取款修改)
// 2. 构造方法:创建账户时必须传入账号和户主姓名,余额初始为0
public BankAccount(String accountNumber, String ownerName) {
this.accountNumber = accountNumber;
this.ownerName = ownerName;
this.balance = 0.0;
}
// 3. Getter方法(对外提供查询)
// 账号只有getter,没有setter,保证不可修改
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. 存款方法 deposit
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("存款成功!当前余额:" + balance);
} else {
System.out.println("存款失败!存款金额必须大于0。");
}
}
// 6. 取款方法 withdraw
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("取款成功!当前余额:" + balance);
} else if (amount <= 0) {
System.out.println("取款失败!取款金额必须大于0。");
} else {
System.out.println("取款失败!余额不足。");
}
}
// 测试主方法(可选,用来验证功能)
public static void main(String[] args) {
// 创建一个账户
BankAccount account = new BankAccount("622202123456789", "张三");
// 测试查询
System.out.println("账号:" + account.getAccountNumber());
System.out.println("户主:" + account.getOwnerName());
System.out.println("初始余额:" + account.getBalance());
// 测试存款
account.deposit(500);
account.deposit(-100); // 测试错误存款
// 测试取款
account.withdraw(200);
account.withdraw(400); // 测试余额不足
account.withdraw(-50); // 测试错误取款
}
}