練習目標-Java 語言中面向對象的封裝性及構造器的使用。
任務
在這個練習里,創建一個簡單版本的(賬戶類)Account類。將這個源文件放入banking程序包中。在創建單個帳戶的默認程序包中,已編寫了一個測試程序TestBanking。這個測試程序初始化帳戶余額,並可執行幾種簡單的事物處理。最后,該測試程序顯示該帳戶的最終余額。

1.創建banking 包
2.在banking 包下創建Account類。該類必須實現上述UML框圖中的模型。
a.聲明一個私有對象屬性:balance,這個屬性保留了銀行帳戶的當前(或即時)余額。
b.聲明一個帶有一個參數(init_balance)的公有構造器,這個參數為balance屬性賦值。
c.聲明一個公有方法getBalance,該方法用於獲取經常余額。
d.聲明一個公有方法deposit,該方法向當前余額增加金額。
e.聲明一個公有方法withdraw從當前余額中減去金額。
3.編譯TestBanking.java文件。
4.運行TestBanking類。可以看到下列輸出結果:
Creating an account with a 500.00 balance
Withdraw 150.00
Deposit 22.50
Withdraw 47.62
The account has a balance of 324.88
///Class Account
package banking;
public class Account {
private double balance;
public Account(double i)
{
balance=i;
}
public double getBalance()
{
return balance;
}
public void deposit(double i)
{
balance+=i;
System.out.println("Deposit "+i);
}
public void withdraw(double i)
{
if(balance>=i)
{
balance-=i;
System.out.println("Withdraw "+i);
}
else
{
System.out.println("余額不足");
}
}
}
//Testbanking
package banking;
public class TestBanking {
public static void main(String[] args) {
Account a=new Account(500.00);
System.out.println("Creating an account with a "+a.getBalance()+"balance");
a.withdraw(150.00);
a.deposit(22.50);
a.withdraw(47.62);
System.out.println("The account has a balance of "+a.getBalance());
//運行結果
Creating an account with a 500.0balance
Withdraw 150.0
Deposit 22.5
Withdraw 47.62
The account has a balance of 324.88
