admin管理员组

文章数量:1648356

练习1、在银行项目中创建Account的两个子类:SavingAccount和CheckingAccount

实训目的:
继承、多态、方法的重写。
提示:
创建Account 类的两个子类:SavingAccount和CheckingAccount子类
a. 修改Account 类;将balance 属性的访问方式改为protected
b. 创建SavingAccount类,该类继承Account 类
c. 该类必须包含一个类型为double 的interestRate属性
d. 该类必须包括带有两个参数(balance 和interest_rate)的公有构造器。该构造器必须通过调用super(balance)将balance 参数传递给父类构造器。

实现CheckingAccount类
1.CheckingAccount类必须扩展Account 类
2.该类必须包含一个类型为double 的overdraftProtection属性。
3.该类必须包含一个带有参数(balance)的共有构造器。该构造器必须通过调用super(balance)将balance 参数传递给父类构造器。
4.给类必须包括另一个带有两个参数(balance 和protect)的公有构造器。该构造器必须通过调用super(balance)并设置overdragtProtection属性,将balance 参数传递给父类构造器。
5.CheckingAccount类必须覆盖withdraw 方法。此方法必须执行下列检查。如果当前余额足够弥补取款amount,则正常进行。如果不够弥补但是存在透支保护,则尝试用overdraftProtection得值来弥补该差值(balance-amount)。如果弥补该透支所需要的金额大于当前的保护级别。则整个交易失败,但余额未受影响。
6.编写并执行TestBanking程序。

//修改Account 类;将balance 属性的访问方式改为protected

SavingAccount类:

package banking;

public class SavingAccount extends Account {
   

	//声明一个私有变量interestRate表示利率
	private double interestRate;
	public SavingAccount(double balance,double interestRate) {
   
		super(balance);
		this.interestRate =interestRate; 
	}
	
}

CheckingAccount类:

package banking;

public class CheckingAccount extends Account{
   

	//声明一个变量overdraftProtection用来表示可以透支的额度
	private double overdraftProtection;
	
	public CheckingAccount(double balance) {
   
		super(balance);
	}
	public CheckingAccount(double balance,double overdraftProtection) {
   
		super(balance);
		this.overdraftProtection = overdraftProtection;
	}
	@Override
	public boolean withdraw(double amt) {
   
		// 如果当前余额足够弥补取款amount,则正常进行
		// 如果不够弥补但是存在透支保护,
		// 则尝试用overdraftProtection得值来弥补该差值(balance-amount)
		if (balance >= amt) {
   
			balance-=amt;
			return true;
		}else if (overdraftProtection +balance>= amt){
   
			amt -=balance;
			overdraftProtection -=amt;
			// 对balance设置值为0
			this.balance = 0;
			return true;
		}
		return false;
	}
}

package banking;

import org.omg.CORBA.PRIVATE_MEMBER;

本文标签: 子类模块两个Account