接口練習——模拟銀行存取款
要求:
1、 建立基接口BankAccount,包含 存款方法playIn(),取款方法withdraw(),查詢餘額方法getBalance()。
2、 建立接口ITransferBankAccount(繼承基接口BankAccount),包含轉賬方法transferTo().
3、 建立類CurrentAccount(實作基接口ITransferBankAccount),類中包含私有資料成員:名字name和餘額balance
,并實作存款方法:playIn(),取款方法:withdraw(),查詢餘額getBanlance(),銀行轉賬方法transferTo(),
重載方法toString()方法,該方法傳回銀行目前賬戶中的餘額。
4、 主函數中:擁有兩個賬戶:分别為曹操和劉備,(1):曹操存款1000,劉備存款2000。 (2):劉備向曹操轉賬1元錢,傳回兩個賬戶目前的餘額。
interface BankAccount{
void playIn(int money);
void withdraw(int money);
int getBalance();
}
interface ITransferBankAccount extends BankAccount{
void transferTo(CurrentAccount ca,int money);
}
class CurrentAccount implements ITransferBankAccount{
private String name;
private int balance;
public CurrentAccount(String name, int balance) {
super();
this.name = name;
this.balance = balance;
}
@Override
public void playIn(int money) {
// TODO Auto-generated method stub
this.balance = this.balance+money;
}
@Override
public void withdraw(int money) {
// TODO Auto-generated method stub
this.balance = this.balance-money;
}
@Override
public int getBalance() {
// TODO Auto-generated method stub
return balance;
}
@Override
public void transferTo(CurrentAccount ca,int money) {
// TODO Auto-generated method stub
ca.balance = ca.balance+money;
this.balance = this.balance-money;
}
}
public class Test5 {
public static void main(String[] args) {
CurrentAccount caocao = new CurrentAccount("caocao",);
CurrentAccount liubei = new CurrentAccount("liubei",);
caocao.playIn();
liubei.playIn();
liubei.transferTo(caocao, );;
System.out.println("caocao balance :"+caocao.getBalance());
System.out.println("liubei balance :"+liubei.getBalance());
}
}
運作結果: