实验题目
扩展银行项目,添加一个 Customer 类。Customer 类将包含一个 Account对 象。
实验目的
使用引用类型的成员变量。
提 示
- 在banking包下的创建Customer类。该类必须实现上面的UML图表中的模 型。
- 声明三个私有对象属性:firstName、lastName 和 account。
- 声明一个公有构造器,这个构造器带有两个代表对象属性的参数(f 和 l)
- 声明两个公有存取器来访问该对象属性,方法 getFirstName 和 getLastName 返 回相应的属性。
- 声明 setAccount 方法来对 account 属性赋值。
- 声明 getAccount 方法以获取 account 属性。
- 在 exercise2 主目录里,编译运行这个 TestBanking 程序。应该看到如下 输出结果:
CreatingthecustomerJaneSmith. Creatingheraccountwitha500.00balance. Withdraw150.00Deposit22.50Withdraw47.62Customer [Smith, Jane] hasabalanceof324.88
代码
【Account.java】类
packagebanking; publicclassAccount { privatedoublebalance; //银行帐户的当前(或即时)余额//公有构造器 ,这个参数为 balance 属性赋值publicAccount(doubleinit_balance) { this.balance=init_balance; } //用于获取经常余额publicdoublegetBalance() { returnbalance; } //向当前余额增加金额publicvoiddeposit(doubleamt){ balance+=amt; } //从当前余额中减去金额publicvoidwithdraw(doubleamt){ balance-=amt; } }
【Customer.java】类
packagebanking; publicclassCustomer { privateStringfirstName; privateStringlastName; privateAccountaccount; publicCustomer(Stringf, Stringl) { this.firstName=f; this.lastName=l; } publicStringgetFirstName() { returnfirstName; } publicStringgetLastName() { returnlastName; } publicAccountgetAccount() { returnaccount; } publicvoidsetAccount(Accountacct) { this.account=acct; } }
【TestBanking.java】类
packagebanking;/** This class creates the program to test the banking classes.* It creates a new Bank, sets the Customer (with an initial balance),* and performs a series of transactions with the Account object.*/importbanking.*; publicclassTestBanking { publicstaticvoidmain(String[] args) { Customercustomer; Accountaccount; // Create an account that can has a 500.00 balance.System.out.println("Creating the customer Jane Smith."); //codecustomer=newCustomer("Jane","Smith"); System.out.println("Creating her account with a 500.00 balance."); //codeaccount=newAccount(500.00); customer.setAccount(account); System.out.println("Withdraw 150.00"); //codecustomer.getAccount().withdraw(150.00); System.out.println("Deposit 22.50"); //codecustomer.getAccount().deposit(22.50); System.out.println("Withdraw 47.62"); //codecustomer.getAccount().withdraw(47.62); // Print out the final account balanceSystem.out.println("Customer ["+customer.getLastName() +", "+customer.getFirstName() +"] has a balance of "+account.getBalance()); } }