*(1)在下面类的基础上扩展新类:CheckingAccount,对每一次存款和取款都收取1美元的手续费
*(2)扩展前一个练习的BankAccount类,新类SavingsAccount每个月都有利息(0.01)产生,
* (earnMonthlyInterest方法被调用),并且每月有三次的免手续费的存款或取款。
* 在earnMonthlyInterest方法中重置交易次数
* */
public class BankAccount {
private double balance;//余额
public BankAccount(double balance) {
this.balance = balance;
}
//存款
public void deposit(double amount){
balance += amount;
}
//取款
public void withdraw(double amount){
balance -= amount;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}
//对每一次存款和取款都收取1美元的手续费
public class CheckingAccount extends BankAccount{
public CheckingAccount(double balance) {
super(balance);
}
//重写存款方法,因为要收取一美元的手续费,所以存入的金额要少一块给到银行的账户
@Override
public void deposit(double amount) {
super.deposit(amount-1);
}
//重写取款方法,因为要收取一美元的手续费,所以取出来的金额要多取一块给到银行的账户
@Override
public void withdraw(double amount) {
super.withdraw(amount+1);//多取一块钱
}
}
/*扩展前一个练习的BankAccount类,新类SavingsAccount每个月都有利息(0.01)产生(earnMonthlyInterest方法被调用),
并且每月有三次的免手续费的存款或取款。
* 在earnMonthlyInterest方法中重置交易次数*/
public class SavingsAccount extends BankAccount{
//属性:利息、免费三次存取次数
private double interest=0.1;//利息
private int count=3;//存取次数,将其初始化为3次,当用一次就减少一次
//构造器定义出利息,因为是变化的,所以可以设置,也可以设置成定量,则不写入构造器就行
public SavingsAccount(double balance) {
super(balance);
}
//重写一下存取款的方法,因为有了利率后,余额又有变化
@Override//存款
public void deposit(double amount) {
if (count>0) {//如果次数大于0,也就是还未取到3次
super.deposit(amount);
}else {
super.deposit(amount-1);
}
count--;
}
@Override//取款
public void withdraw(double amount) {
if (count>0) {//如果次数大于0,也就是还未取到3次
super.withdraw(amount);
}else {
super.withdraw(amount-1);
}
count--;
}
//每个月都有利率(0.01)产生(earnMonthlyInterest方法被调用)
// 在earnMonthlyInterest方法中重置交易次数
public void earnMonthlyInterest(){
count=3;//重置次数
super.deposit(getBalance()*interest);
}
public double getInterest() {
return interest;
}
public void setInterest(double interest) {
this.interest = interest;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
public class Test08 {
public static void main(String[] args) {
//测试 SavingsAccount类
SavingsAccount savingsAccount = new SavingsAccount(1000);
savingsAccount.deposit(100);
savingsAccount.deposit(100);
savingsAccount.deposit(100);
System.out.println(savingsAccount.getBalance());
savingsAccount.withdraw(100);//这是第四次了
System.out.println(savingsAccount.getBalance());
savingsAccount.earnMonthlyInterest();//一个月了重置次数,并且计算了利率
System.out.println(savingsAccount.getBalance());
}
}
输出:
1300.0
1201.0
1321.1
面向对象练习题---银行存取系统
最新推荐文章于 2022-09-27 22:01:00 发布