作業要求:1.寫一個名為Account的類模拟賬戶。該類的屬性和方法如下所示:該類包括的屬性: ID,餘額balance,年利率;包含的方法:各屬性的set和get方法。取款方法withdraw ( ) ,存款方法deposit ( )......
作業要求:
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) ̄)ブ