练习:用List表示多重性
练习目标-在类中使用List作为模拟集合操作: 在本练习中,将用List实现银行与客户间的多重关系。
任务:对银行来说,可添加Bank类。 Bank 对象跟踪自身与其客户间的关系。用Customer对象的List实现这个集合化的关系。还要保持一个整数属性来跟踪银行当前有多少客户
1、创建 Bank
2、Bank类增加两个属性:customers(Customer对象的List)和numberOfCustomers(整数, 当前Customer对象的数量)
3、添加公有构造器,初始化customersList。
4、添加addCustomer方法。该方法必须依照参数(姓,名)构造一个新的Customer对象然后把它放到customerList中。
5、添加getNumOfCustomers 访问方法,它返回numberofCustomers属性值。
6、添加getCustomer方法。它返回与给出的index参数相关的客户。
7、编译并运行TestBanking程序。可以看到下列输出结果:
Customer 1 is Simms,Jane
Customer 2 is Bryant,Owen
Customer 3 is Soley,Tim
Customer 4 is Soley,Maria
当前客户数量 = 4
import java.util.ArrayList; import java.util.List; public class Bank{ private List<Customer> customers; //customers集合 private int numberOfCustomers; //记录客户数量 public Bank(){ //构造方法,初始化customers customers=new ArrayList<Customer>(); } public void addCustomer(String f,String l){ //方法:往customers里面添加Customer对象 Customer p=new Customer(f,l); customers.add(p); } public int getNumOfCustomers(){ //获取客户数量,即获取customers的长度 numberOfCustomers=customers.size(); return numberOfCustomers; } public Customer getCustomer(int index){ //根据索引取值return customers.get(index); } }
public class TestBanking { public static void main(String[] args) { Bank cus=new Bank(){}; cus.addCustomer("Simms", "Jane"); cus.addCustomer("Bryant", "Owen"); cus.addCustomer("Soley","Tim"); cus.addCustomer("Soley","Maria"); for(int i=0;i<cus.getNumOfCustomers();i++){ System.out.println("Customer "+(i+1)+" is"+" "+cus.getCustomer(i)); } System.out.println("当前客户数量="+cus.getNumOfCustomers()); System.out.println("第二个客户是:"+cus.getCustomer(2)); } }
运行结果:
Customer类:
public class Customer { //声明私有属性 private String firstName; private String lastName; private Account account; //声明构造器 Customer(){}; Customer(String f,String l){ this.firstName=f; this.lastName=l; } //声明存取器getter/setter方法 public String getFirstName() { //firstName return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { //lastName return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } //存取器getter/setter方法——account public Account getAccount() { return account; } public void setAccount(Account acct) { this.account=acct; } @Override public String toString() { return firstName + "," + lastName; } }
时间: 2024-11-05 06:22:10