java银行账户管理系统简单源代码
时间: 2024-10-12 17:09:46 浏览: 51
在Java中设计一个简单的银行账户管理系统,我们可以创建一个基本的体系结构,主要包括`Account`, `SavingsAccount`, 和 `CheckingAccount` 类。这里我将给出一个简化的示例:
```java
// 定义一个抽象的Account类作为基础
public abstract class Account {
private String accountNumber;
private double balance;
public Account(String accountNumber) {
this.accountNumber = accountNumber;
this.balance = 0;
}
// 公共方法
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
} else {
System.out.println("Insufficient funds.");
}
}
public double getBalance() {
return balance;
}
// 抽象方法,需要在子类中实现
public abstract double calculateInterest();
}
// 子类SavingsAccount和CheckingAccount分别实现不同的利率计算
public class SavingsAccount extends Account {
public SavingsAccount(String accountNumber) {
super(accountNumber);
}
@Override
public double calculateInterest() {
return balance * 0.03; // 假设年利率为3%
}
}
public class CheckingAccount extends Account {
public CheckingAccount(String accountNumber) {
super(accountNumber);
}
@Override
public double calculateInterest() {
if (balance < 500) {
return 0;
} else {
return balance * 0.01; // 假设年利率为1% for balance above $500
}
}
}
// 主程序入口
public class BankAccountManager {
public static void main(String[] args) {
Account myAccount = new SavingsAccount("123456789");
myAccount.deposit(1000);
System.out.println("Initial balance: " + myAccount.getBalance());
myAccount.withdraw(200);
System.out.println("After withdrawal: " + myAccount.getBalance());
// 调用子类方法
double savingsInterest = ((SavingsAccount) myAccount).calculateInterest();
System.out.println("Savings interest: " + savingsInterest);
CheckingAccount checkingAccount = new CheckingAccount("987654321");
System.out.println("Checking account interest: " + checkingAccount.calculateInterest());
}
}
```
阅读全文