自建异常类、
public class overdraw extends Exception{
String message;
overdraw(int n)
{
message="余额不足,不能取"+n;
}
public String getmessage()
{
return message;
}
public void setmessage(String n)
{
message=n;
}
}
bank类,里面有储户
public class bank {
List<customer> cus =new LinkedList<customer>();
public void addcustomer(customer obj)
{
cus.add(obj);
}
public customer getcus(int n)
{
return cus.get(n);
}
}
customer类,里面 链表 存账号
注意1.list写法格式
2.返回it的格式
3.getaccount(int n)直接return list.get(n)就完事了
public class customer {
String name;
List<acount> accounts=new ArrayList<acount>();//生命一个类型为。。。的列表
public customer(String name)
{
this.name=name;
}
public Iterator<acount> getacount()//getAccounts方法返回该储户的帐号的Iterator,以便获得每个帐号对象。
{
Iterator<acount> it= accounts.iterator();
return it;
}
public void addaccount(acount obj)
{
accounts.add(obj);
}
public acount getacc(int n)
{
return accounts.get(n);
}
}
抽象类accout
public abstract class acount {
int balance;
acount(int balance)
{
this.balance=balance;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public void withdrow(int n)throws overdraw
{if(balance<n)
{
overdraw ex=new overdraw(n);
throw(ex);
}
else {
this.balance -= n;
}
}
public String toString()
{
return "account{余额为:"+balance+"}";
}
}
大额账号
注意异常写法
super位置
重写 了 抽象类的 抛异常函数,用setmeaaasge设置新的异常提示
public class CheckingAccount extends acount{
boolean canOverdraft;
CheckingAccount(int balance,boolean canOverdraft){//super必须写在前边
super(balance);
this.canOverdraft=canOverdraft;
}
public void withdrow(int n)throws overdraw//重写这个带有异常的方法
{
if(canOverdraft==false)
{
overdraw ex=new overdraw(n);
ex.setmessage("不允许透支");//重设置异常输出
throw ex;
}
if(balance<n)
{
overdraw ex=new overdraw(n);
throw(ex);
}
else {
this.balance -= n;
}
}
}
testl
public class test {
public static void main(String[] args) {
CheckingAccount obj=new CheckingAccount(100,true);
CheckingAccount obj1=new CheckingAccount(200,true);
/* try{
obj.withdrow(350);
}
catch (overdraw e)
{
System.out.println(e.getmessage());
}*/
bank bank1=new bank();
customer peter =new customer("peter");
peter.addaccount(obj);//可以把aount的子类直接add;
peter.addaccount(obj1);
bank1.addcustomer(peter);
/* while(peter.getacount().hasNext())
{
System.out.println(peter.getacount().next());
}
*/
System.out.println(bank1.getcus(0).getacc(1));
System.out.println(peter.getacc(1));
}
}