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)); } }
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; } }