接口练习——模拟银行存款

模拟银行存取款

1.创建基接口BankAccount。

存款方法playIn()

取款方法withdraw()

查询余额方法getBalance()

2.创建接口ITransferBankAccount(继承基接口BankAccount)

转账方法transferTo()

3.创建类CurrentAccount(实现基接口ITransferBankAccount),类中包含私有数据成员:

名字name

余额balance

存款方法playIn()

取款方法withdraw()

查询余额方法getBalance()

银行转账方法transferTo()

重载方法toString()

4.主函数中:拥有两个账户:分别为曹操和刘备,

(1):曹操存款1000,刘备存款2000。

(2):刘备向曹操转账1元钱,返回两个账户当前的余额。

/**
 * 
 * @author Administrator
 *	 BankAccount 接口
 */
interface BankAccount{
	/**
	 * 
	 * @param balance
	 * 存款方法
	 */
	void playIn(double balance);//存款
	/**
	 * 
	 * @param balance
	 * 取款方法
	 */
	void withdown(double balance);//取款
	/**
	 * 查询余额
	 */
	void getBalance();//查询余额
}
/**
 * 
 * @author Administrator
 * ITransferBankAccount 接口
 */
interface ITransferBankAccount extends BankAccount{
	void transferTo(CurrentAccount a,Double balance);//转账;
}
/**
 * 
 * @author Administrator
 * 账户类 ,实现 ITransferBankAccount 接口方法
 */
class CurrentAccount implements ITransferBankAccount{
	/**
	 * 账户名
	 */
	private String name;
	/**
	 * 账户余额
	 */
	private double balance;
	/**
	 * 
	 * @param name
	 * 账户的构造方法
	 */
	public CurrentAccount(String name) {
		this.name = name;
		this.balance = 0.0;
	}
	@Override
	public String toString() {
		return "CurrentAccount [balance=" + balance + "]";
	}

	@Override
	public void playIn(double balance) {
		this.balance += balance; 
		System.out.println(this.name+"存款 "+balance+" 成功");
	}

	@Override
	public void withdown(double balance) {
		if(this.balance < balance){
			System.out.println("余额不足。");
		}
		this.balance -= balance; 	
	}

	@Override
	public void getBalance() {
		System.out.println(this.name+" 的账户余额为:"+this.balance);
	}

	@Override
	public void transferTo(CurrentAccount a,Double balance) {
		if(this.balance < balance){
			System.out.println("余额不足。");
			return ;
		}
		this.balance -= balance;
		a.balance  += balance;
		System.out.println(this.name+" 给 "+a.name+" 转账 "+balance+" 元成功");
	}
}

public static void main(String[] args) {
		CurrentAccount cao = new CurrentAccount("曹操");
		CurrentAccount liu = new CurrentAccount("刘备");
		cao.playIn(1000.0);
		liu.playIn(2000.0);
		cao.transferTo(liu, 1.0);
		cao.getBalance();
		liu.getBalance();	
	}

运行结果:

曹操存款 1000.0 成功

刘备存款 2000.0 成功

曹操 给 刘备 转账 1.0 元成功

曹操 的账户余额为:999.0

刘备 的账户余额为:2001.0

猜你喜欢

转载自blog.csdn.net/alyson_jm/article/details/80448111