作业要求:
1.写一个名为Account的类模拟账户。该类的属性和方法如下所示:
该类包括的属性: ID,余额balance,年利率;
包含的方法:各属性的set和get方法。取款方法withdraw ( ) ,存款方法deposit ( );
2.写一个测试程序:
创建一个Customer,名字叫王狗蛋, 他有一个账号为1314,余额为2000,年利率为1.23的账户,对王狗蛋的账户1314进行操作:
存入100元,再取出960元,再取出2000;
信息如下显示:
成功存入: 100
成功取出: 960
余额不足,取钱失败
public class 银行虚拟账户管理 { public static void main(String[] args) { Account a= new Account("1314", 2000, 1.23); //把账户a给了c(王狗蛋) Customer c=new Customer("王狗蛋",a); /*c.act...再进行对账户的操作是错误的因为act是私有的,只能通过公共方法对其进行操作,可以用a.对账户进行操作,但是这样就失去了面向对象 的思想,现在账户a是c的,c是取钱存钱的那个人,所以只有c.可以对他的账户a进行操作,而用c.act.是错误的,因为act相对于用户是私有属性, 所以只能通过人为设置的入口对其操作:c.getAct().deposit(); 等价于 act.deposit(); 虽然等价但是前者才是正确书写*/ c.getAct().deposit(100); c.getAct().withdraw(960); c.getAct().withdraw(2000); } } class Customer{ protected String name; protected Account act; public Customer(){ } public Customer(String name,Account act){ this.name=name; this.act=act; } public void setName(String name){ this.name=name; } public void setAct(Account act){ this.act=act; } public String getName(){ return name; } public Account getAct(){ return act; } } class Account{ protected String id; protected double balance; protected double nianLiLv; public Account(){ this(null,0,0); } public Account(String id,double balance,double nianLiLv){ this.id=id; this.balance=balance; this.nianLiLv=nianLiLv; } public void setId(String id){ this.id=id; } public void setBalance(double balance){ this.balance=balance; } public void setNianLiLv(double nianLiLv){ this.nianLiLv=nianLiLv; } public String getId(){ return id; } public double getBalance(){ return balance; } public double getNianLiLv(){ return nianLiLv; } public void withdraw(int i1){ if(i1>balance){ System.out.println("余额不足,取款失败"); } else { System.out.println("成功取出:" + i1); //balance -= i1;---第一种写法 //this.setBalance(balance-i1);---第二种写法 this.setBalance(this.getBalance()-i1);//---第三种写法 } } public void deposit(int i1){ System.out.println("成功存入:"+i1); balance+=i1; } }
输出结果:
成功存入:100 成功取出:960 余额不足,取款失败 Process finished with exit code 0
能力有限,若程序有bug或有其他不当之处,请狠狠打脸博主 (~ ̄(OO) ̄)ブ