Java学习笔记(十一)

Java学习笔记(十一)

用面向对象的编程思想去理解:银行,账户,客户之间的关系。

1.银行索引客户,客户索引账户;

2.金钱的加减在账户中进行。

下面给出代码:

账户

public class Account {
	private double balance;
	public Account(double init_balance) {
		balance = init_balance;
	}
	public double getBalance() {
		
		return balance;
	}
	public void withdraw(double amt) {
		if (amt > balance) {
			System.out.println("余额为"+balance+"小于取款额");
		}else {
			balance -= amt;
			System.out.println("本次取钱"+amt+"余额为"+balance);
		}
	}
	public void deposit(double amt) {
		balance += amt;
		System.out.println("本次存钱"+amt+"余额为"+balance);
	}
	
}

客户

public class Customer {
	private String firstName;
	private String lastName;
	private Account account;
	public Customer() {
		
	}
	public Customer(String f,String l) {
		firstName = f;
		lastName = l;
		
	}
	public String getFirstName() {
		return firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public Account getAccount() {
		return account;
	}
	public void setAccount(Account acct) {
		account = acct;
	};
	
}

银行

public class Bank {
	private Customer[] customers = new Customer[10];
	private int numberOfCustomer;

	public Bank() {
//		customers = new Customer[10];
	}
	public void addCustomer(String f,String l) {
		Customer cust  = new Customer(f,l);
		customers[numberOfCustomer] = cust;
		numberOfCustomer++;
	}
	public int getNumOfCustomer() {
		return numberOfCustomer;
	}
	public Customer getCustomer(int index) {
		if (index >= 0 && index < numberOfCustomer) {
			return customers[index];
		}
		return null;
	}
}

整个系统的测试

在测试代码中,得清楚的知道这一层一层代码的索引值是什么,是地址还是真实的值。

public class BankTest {
	public static void main(String[] args) {
		Account account = new Account(50045);
		Customer cust = new Customer("li","weixiang");
		cust.setAccount(account);
		Bank bank = new Bank();
		bank.addCustomer("li", "weixiang");
		bank.getCustomer(0).setAccount(account);
		bank.getCustomer(0).getAccount().withdraw(45);
		double balance = bank.getCustomer(0).getAccount().getBalance();
		System.out.println(balance);
		System.out.println("********************");
		bank.addCustomer("liu", "xingrui");
		bank.getCustomer(1).setAccount(new Account(34567));
		System.out.println("银行账户现在有:"+bank.getNumOfCustomer()+"个");
	}
}

你可能感兴趣的:(Java)