用Java写一个关于checkingaccount和bankaccount的代码
时间: 2024-04-30 07:22:35 浏览: 53
以下是一个简单的java代码示例,实现了一个CheckingAccount和BankAccount类,包括了基本的属性和方法。
CheckingAccount类:
```
public class CheckingAccount extends BankAccount {
private double transactionFee;
public CheckingAccount(double balance, double transactionFee) {
super(balance);
this.transactionFee = transactionFee;
}
public void deductTransactionFee() {
double fee = transactionFee * getNumTransactions();
withdraw(fee);
}
}
```
BankAccount类:
```
public class BankAccount {
private double balance;
private int numTransactions;
public BankAccount(double balance) {
this.balance = balance;
this.numTransactions = 0;
}
public void deposit(double amount) {
balance += amount;
numTransactions++;
}
public void withdraw(double amount) {
balance -= amount;
numTransactions++;
}
public double getBalance() {
return balance;
}
public int getNumTransactions() {
return numTransactions;
}
}
```
在CheckingAccount类中,我们添加了一个transactionFee属性和deductTransactionFee()方法。该方法会根据transactionFee和账户的交易次数计算出手续费,并从账户余额中扣除手续费。
BankAccount类包括了基本的属性和方法,如deposit()、withdraw()、getBalance()和getNumTransactions()等。
使用这两个类,我们可以创建一个CheckingAccount对象和一个BankAccount对象,并对它们执行一些操作:
```
CheckingAccount checkingAccount = new CheckingAccount(1000, 0.01);
BankAccount bankAccount = new BankAccount(500);
checkingAccount.deposit(200);
bankAccount.withdraw(100);
checkingAccount.deductTransactionFee();
System.out.println("Checking account balance: " + checkingAccount.getBalance());
System.out.println("Bank account balance: " + bankAccount.getBalance());
```
输出:
```
Checking account balance: 1199.98
Bank account balance: 400.0
```
在这个例子中,我们创建了一个初始余额为1000、transactionFee为0.01的CheckingAccount对象和一个初始余额为500的BankAccount对象。然后我们对这两个账户执行了一些操作,包括存款、取款和扣除手续费。最后,我们输出了两个账户的余额。
阅读全文