模拟银行账户管理Java
时间: 2024-10-11 22:14:56 浏览: 23
java语言模拟银行账户功能
模拟银行账户管理在Java中通常涉及创建一个BankAccount类,它作为父类或者抽象类,包含了账户的基本属性如账户号码(account number)、余额(balance)以及一些基本操作方法,比如存款(deposit)、取款(withdraw)和查看余额(view balance)。
```java
public abstract class BankAccount {
private String accountNumber;
protected double balance;
public BankAccount(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
setBalance(initialBalance);
}
// getter and setter methods for accountNumber and balance
public String getAccountNumber() { return accountNumber; }
public void setAccountNumber(String accountNumber) { this.accountNumber = accountNumber; }
public double getBalance() { return balance; }
public void setBalance(double balance) { if (balance >= 0) this.balance = balance; else throw new IllegalArgumentException("Balance cannot be negative"); }
// Abstract method for withdrawal
public abstract boolean withdraw(double amount);
// Concrete method for deposit
public boolean deposit(double amount) {
if (amount > 0) {
balance += amount;
return true;
} else {
throw new IllegalArgumentException("Deposit amount must be positive");
}
}
// Method to view balance
public void viewBalance() {
System.out.println("Current balance: " + balance);
}
}
// Concrete classes like SavingsAccount or CheckingAccount extend BankAccount
class SavingsAccount extends BankAccount {
@Override
public boolean withdraw(double amount) {
// Implement savings account specific withdrawal logic here
}
}
class CheckingAccount extends BankAccount {
@Override
public boolean withdraw(double amount) {
// Implement checking account specific withdrawal logic here
}
}
```
阅读全文