用java创建一个名为BankAccount的抽象类,具有两个名为deposit()和withdraw()的抽象方法。创建两个子类CheckingAccount和SavingsAccount,并实现它们各自的deposit()和withdraw()方法。在Main类中创建一个BankAccount数组并用不同类型的账户对象填充它,然后循环遍历该数组并对每个账户对象执行一些存款和取款操作。
时间: 2023-12-14 15:36:20 浏览: 91
JAVA实现银行账户类
5星 · 资源好评率100%
以下是Java代码实现:
```java
// BankAccount.java
public abstract class BankAccount {
public abstract void deposit(double amount);
public abstract void withdraw(double amount);
}
// CheckingAccount.java
public class CheckingAccount extends BankAccount {
private double balance;
public CheckingAccount(double balance) {
this.balance = balance;
}
@Override
public void deposit(double amount) {
balance += amount;
}
@Override
public void withdraw(double amount) {
balance -= amount;
}
}
// SavingsAccount.java
public class SavingsAccount extends BankAccount {
private double balance;
public SavingsAccount(double balance) {
this.balance = balance;
}
@Override
public void deposit(double amount) {
balance += amount;
}
@Override
public void withdraw(double amount) {
if (balance - amount < 0) {
System.out.println("Insufficient funds.");
return;
}
balance -= amount;
}
}
// Main.java
public class Main {
public static void main(String[] args) {
BankAccount[] accounts = new BankAccount[2];
accounts[0] = new CheckingAccount(1000);
accounts[1] = new SavingsAccount(2000);
for (BankAccount account : accounts) {
account.deposit(500);
account.withdraw(200);
}
}
}
```
在这个例子中,我们创建了一个抽象类BankAccount,它有两个抽象方法deposit()和withdraw()。然后我们创建了两个子类CheckingAccount和SavingsAccount,并分别实现它们的deposit()和withdraw()方法。
在Main类中,我们创建了一个BankAccount数组并用不同类型的账户对象填充它。然后我们循环遍历该数组并对每个账户对象执行一些存款和取款操作。这样我们就可以测试不同类型的账户对象在执行相同的操作时的行为。
阅读全文