练习2
练习目标-使用引用类型的成员变量:在本练习中,将扩展银行项目,添加一个(客户类)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
//Customer类
package banking;
public class Customer {
private String firstName,lastName;
private Account account;
public Customer(String f,String l)
{
firstName=f;
lastName=l;
System.out.println("Creating the customer "+f+" "+l);
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
//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());
Customer c=new Customer("Jane", "Smith");
Account b=new Account(500.00);
c.setAccount(b);
a=c.getAccount();
System.out.println("Creating her account with a "+a.getBalance()+"balance");
a.withdraw(150.00);
a.deposit(22.50);
a.withdraw(47.62);
System.out.println("Customer ["+c.getFirstName()+","+c.getLastName()+"] 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
Creating the customer Jane Smith
Creating her account with a 500.0balance
Withdraw 150.0
Deposit 22.5
Withdraw 47.62
Customer [Jane,Smith] has a balance of 324.88