(1)创建基接口IBankAccount,包含存款方法payIn()、取款方法withdraw()、查询余额方法getBalance()。
(2)创建接口ITransferBankAccount(继承基接口IBankAccount),包含转账方法transferTo()。
(3)创建类CurrentAccount(实现基接口ITransferBankAccount),包含私有数据成员balance,并实现存款方法payIn()、取款方法withdraw()、查询余额getBalance()、银行转账方法transferTo()、重载toString()方法,返回银行当前账户中的余额。
//InterfaceInheritDemo.java
interface IBankAccount{//银行账户
void payIn(double amount);//存款
boolean withdraw(double amount);//取款,返回是否成功
double getBalance();//余额
}
interface ITransferBankAccount extends IBankAccount{//转账银行账户
boolean transferTo(IBankAccount destination,double amount);//转账
}
class CurrentAccount implements ITransferBankAccount{//当前账户
public String name;
private double balance;
public CurrentAccount(String name){
this.name=name;
}
@Override
public void payIn(double amount) {
// TODO Auto-generated method stub
this.balance+=amount; //存款
}
@Override
public boolean withdraw(double amount) {//账户有足够的余额,则取款,并返回是否成功
// TODO Auto-generated method stub
if(this.balance>=amount){
this.balance-=amount;
return true;
}
System.out.println("余额不足,取款失败!");
return false;
}
@Override
public double getBalance() {//返回余额
// TODO Auto-generated method stub
return this.balance;
}
@Override
public boolean transferTo(IBankAccount destination, double amount) {//银行转账
// TODO Auto-generated method stub
boolean result;
if((result=withdraw(amount))==true)
destination.payIn(amount);
return result;
}
public String toString(){//返回银行当前账户中的余额,重写从object中继承的方法toString()
return String.format("账户(%S):余额=%9.2f",this.name,this.balance);
}
}
public class InterfaceInheritDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
IBankAccount bankCount1=new CurrentAccount("张三");//账户1
ITransferBankAccount bankCount2=new CurrentAccount("李四");//账户2
bankCount1.payIn(200);//账户1,存款200
bankCount2.payIn(500);//账户2,存款500
bankCount2.transferTo(bankCount1, 100);//账户2转账100到账户1
//显示账户余额
System.out.println(bankCount1.toString());
System.out.println(bankCount2.toString());
}
}
运行结果:
账户(张三):余额= 300.00
账户(李四):余额= 400.00