持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第29天,点击查看活动详情
实验题目
扩展银行项目,添加一个 Customer 类。Customer 类将包含一个 Account对 象。
实验目的
使用引用类型的成员变量。
提 示
-
在banking包下的创建Customer类。该类必须实现上面的UML图表中的模 型。
- 声明三个私有对象属性:firstName、lastName 和 account。
- 声明一个公有构造器,这个构造器带有两个代表对象属性的参数(f 和 l)
- 声明两个公有存取器来访问该对象属性,方法 getFirstName 和 getLastName 返 回相应的属性。
- 声明 setAccount 方法来对 account 属性赋值。
- 声明 getAccount 方法以获取 account 属性。
-
在 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
代码
【Account.java】类
package banking;
public class Account {
private double balance; //银行帐户的当前(或即时)余额
//公有构造器 ,这个参数为 balance 属性赋值
public Account(double init_balance) {
this.balance = init_balance;
}
//用于获取经常余额
public double getBalance() {
return balance;
}
//向当前余额增加金额
public void deposit(double amt){
balance+=amt;
}
//从当前余额中减去金额
public void withdraw(double amt){
balance-=amt;
}
}
【Customer.java】类
package banking;
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;
}
}
【TestBanking.java】类
package banking;/*
* This class creates the program to test the banking classes.
* It creates a new Bank, sets the Customer (with an initial balance),
* and performs a series of transactions with the Account object.
*/
import banking.*;
public class TestBanking {
public static void main(String[] args) {
Customer customer;
Account account;
// Create an account that can has a 500.00 balance.
System.out.println("Creating the customer Jane Smith.");
//code
customer = new Customer("Jane","Smith");
System.out.println("Creating her account with a 500.00 balance.");
//code
account = new Account(500.00);
customer.setAccount(account);
System.out.println("Withdraw 150.00");
//code
customer.getAccount().withdraw(150.00);
System.out.println("Deposit 22.50");
//code
customer.getAccount().deposit(22.50);
System.out.println("Withdraw 47.62");
//code
customer.getAccount().withdraw(47.62);
// Print out the final account balance
System.out.println("Customer [" + customer.getLastName()
+ ", " + customer.getFirstName()
+ "] has a balance of " + account.getBalance());
}
}