1 总结: 2 customer.setAccount(account); //引用,日后的account 和 customer.getAccount()的结果始终一致
实验目的
扩展银行项目,添加一个 Customer 类。Customer 类将包含一个 Account对 象。 实验目的: 使用引用类型的成员变量。 提 示: 1. 在banking包下的创建Customer类。该类必须实现上面的UML图表中的模 型。 a. 声明三个私有对象属性:firstName、lastName 和 account。 b. 声明一个公有构造器,这个构造器带有两个代表对象属性的参数(f 和 l) c. 声明两个公有存取器来访问该对象属性,方法 getFirstName 和 getLastName 返 回相应的属性。 d. 声明 setAccount 方法来对 account 属性赋值。 e. 声明 getAccount 方法以获取 account 属性。 2. 在 exercise2 主目录里,编译运行这个 TestBanking 程序。应该看到如下 输出结果: Creating the customer Jane Smith. Creating her account with a 500.00 balance. Withdraw 150.00 Deposit 22.50 Withdraw 47.62 Customer [Smith, Jane] has a balance of 324.88
UML 结构图
工程组织结构:
代码编程:
1/Account.java
package Banking_2; public class Account { private double balance;//余额 ,uml前该变量是 '-' public Account(double init_balance){ balance=init_balance; } public double getBalance() { return balance; } //存钱 public void deposit(double amt){ this.balance+=amt; } //取钱 public void withdraw(double amt){ this.balance-=amt; } }
2/Customer.java
package Banking_2; public class Customer { private String firstName; private String lastName; private Account account; public Customer(String f,String l){ this.firstName=f; this.lastName=l; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public Account getAccount() { return account; } public void setAccount(Account account) { this.account = account; } }
3/新开一个package, 添加测试文件:TestBanking2.java
package TestBanks; import Banking_2.*; public class TestBanking2{ public static void main(String[] args) { Customer customer=new Customer("Jane","Smith"); Account account=new Account(500); // Create an account that can has a 500.00 balance. System.out.println ("Creating the customer Jane Smith."); System.out.println("Creating her account with a 500.00 balance."); customer.setAccount(account); //code System.out.println("Withdraw 150.00"); customer.getAccount().withdraw(150); //code System.out.println("Deposit 22.50"); customer.getAccount().deposit(22.5); //code System.out.println("Withdraw 47.62"); customer.getAccount().withdraw(47.62); //code // Print out the final account balance System.out.println("Customer [" + customer.getLastName() + ", " + customer.getFirstName() + "] has a balance of " + account.getBalance()); //等价于下面的写法 /* System.out.println("Customer [" + customer.getLastName() + ", " + customer.getFirstName() + "] has a balance of " + customer.getAccount().getBalance()); */ } }
运行结果: