快捷搜索: 王者荣耀 脱发

模块二、添加Customer 类

扩展银行项目,添加一个Customer 类。Customer 类将包含一个Account对象。

实训目的: 使用引用类型的成员变量。 提示:

  1. 在banking包下的创建Customer类。该类必须实现上面的UML图表中的模型。 a. 声明三个私有对象属性:firstName、lastName和account。 b. 声明一个公有构造器,这个构造器带有两个代表对象属性的参数(f 和l) c. 声明两个公有存取器来访问该对象属性,方法getFirstName和getLastName返回相应的属性。 d. 声明setAccount方法来对account 属性赋值。 e. 声明getAccount方法以获取account 属性。
  2. 创建TestBanking2类,对Customer和Account进行测试。 3.编译运行这个TestBanking2程序。应该看到如下输出结果: (仅做参考) 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
package banking;

public class Customer {
          
   

	private String firstName;
	private String lastName;
	private Account account;
	
	// 构造方法
	public Customer(String firstName,String lastName) {
          
   
		this.firstName = firstName;
		this.lastName = lastName;
	}

	public String getFirstName() {
          
   
		return firstName;
	}

	public String getLastName() {
          
   
		return lastName;
	}

	public Account getAccount() {
          
   
		return account;
	}

	public void setAccount(Account account) {
          
   
		this.account = account;
	}
	
}

具体实现过程: Customer customer = new Customer(“Jane”, “Smith”);创建一个客户。 Account account = new Account(500);创建一个账户。并将该账户用customer.setAccount(account);分配给该用户。就将客户类和账户类关联起来,可以通过该用户去操作他所拥有的账户。

package banking;

public class TestBanking2 {
          
   

	public static void main(String[] args) {
          
   
		// 创建一个客户
		Customer customer = new Customer("Jane", "Smith");
		// 为customer对象创建一个账户account,并设置初始化金额
		Account account = new Account(500);
		customer.setAccount(account);
		System.out.println("Creating an customer "
				+ customer.getFirstName() +" "+customer.getLastName());
		System.out.println("Creating her account "
				+ "with a "+customer.getAccount().getBalance()+" balance");
		
		// 取钱
		customer.getAccount().withdraw(150.0);
        System.out.println("Withdraw 150.00");
		// 存钱
        customer.getAccount().deposit(22.50);
        System.out.println("Deposit 22.50");
        // 取钱
        customer.getAccount().withdraw(47.62);
        System.out.println("Withdraw 47.62");
        
        System.out.println("Customer ["+customer.getLastName()+","+customer.getFirstName()
        +"] has a balance of "
				+customer.getAccount().getBalance());
	}

}
经验分享 程序员 微信小程序 职场和发展