学习内容:关于构造器的使用,局部变量,属性在内存中的存放,不同类方法之间的调用,形参实参的传递,this关键字,private体现的封装性和JavaBean
题目要求
解答过程
分析: Bank类里有个Customer客户属性,Customer类里有个Account账户属性。
有点类似于Bank嵌套Customer,Customer嵌套Account,Account才最后存了用户的balance
先写Account类
package exer2;
public class Account {
private double balance;
public Account(double init_balance){
this.balance = init_balance;
}
public double getBalance() {
return balance;
}
//存钱
public void deposit(double amt) {
if(amt > 0) {
balance += amt;
System.out.println("存钱成功");
}
}
//取钱
public void withdraw(double amt) {
if(balance >= amt) {
balance -= amt;
System.out.println("取钱成功");
}else {
System.out.println("余额不足");
}
}
}
再写Customer类
package exer2;
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 acct) {
this.account = acct;
}
}
再写Bank类
package exer2;
public class Bank {
private Customer[] customers;//存放多个客户的数组
private int numberOfCustomers;//记录客户个数
//构造器
public Bank() {
//上面的属性只是定义了一个 Customer客户类型的数组
//名字叫做customers,但是在堆中没有开辟空间
//下面就是new了一片空间
customers = new Customer[10];
}
//添加客户
public void addCustomer(String f,String l) {
//为Customer客户类创建对象cust
//并通过Customer构造器将f,l写入
Customer cust = new Customer(f,l);
//把cust用户存到用户数组中,然后在自加加
customers[numberOfCustomers++] = cust;
}
//获取客户的个数
public int getNumOfCustomer() {
return numberOfCustomers;
}
//获取指定位置上的客户
public Customer getCustomer(int index) {
//return customers[index]; //可能报异常
if(index >= 0 && index < numberOfCustomers) {
return customers[index];
}
return null;
}
}
最后进行测试:
BankTest类
package exer2;
public class BankTest {
public static void main(String[] args) {
Bank bank = new Bank();
bank.addCustomer("Jane", "Smith");
//bank.getCustomer(0)找到这个人,再给他set个匿名用户存2000
bank.getCustomer(0).setAccount(new Account(2000));
//花钱
bank.getCustomer(0).getAccount().withdraw(500);
//查查余额
System.out.println("余额为:" + bank.getCustomer(0).getAccount().getBalance());
bank.addCustomer("万里", "杨");
System.out.println("银行现在有了" + bank.getNumOfCustomer() + "个客户。");
}
}
运行结果