我對OOP和Java相當陌生,有一個可能微不足道的問題,但我無法在Web上找到答案。JAVA - 兩個對象之間的關係
我正在做Java中的標準銀行賬戶程序 - 有客戶的程序,每個客戶都有銀行賬戶(一個客戶可能有多個銀行賬戶!),我可以存入或取出資金。每個銀行帳戶都有唯一的編號(即使某人擁有多個銀行帳戶,每個銀行帳戶都有其唯一編號)
我的代碼編譯和操作存取都正常工作。
問題出在以下 - 我不能將多個銀行賬戶歸於客戶,在我的程序中,客戶可以只有一個銀行並且不會超過一個銀行賬戶。
我有3個類 - 帳戶,客戶端,BankMain。你可以看到他們下面
public class Account {
private int balance;
private String NumAccount; // each bank account has a unique number
public Account(int money, String num) {
balance = money;
NumAccount = num;
}
public String printAccountNumber() {
return NumAccount;
}
// below are the methods for withdraw,deposit- they are working properly
}
類客戶端
public class Client {
private String name;// name of the client
private Account account;
// the account associated to the client. Probably I should change sth
// here
// but I don't know what
public Client(String nom, Compte c) {
name = nom;
account = c;
}
public void printName() {
System.out.println(
"Name: " + name
+ "\nAccount number: " + account.printAccountNumber()
+ "\nSolde: " + account.printBalance() + "\n"
);
}
}
而且BankMain
public class BankMain {
public static void main(String[] args) {
Account account1 = new Account(1000, "11223A");
Account account2 = new Account(10000, "11111A");
Client client1 = new Client("George", account1);
Client client2 = new Client("Oliver", account2);
// now this is working correctly
client1.printName();
client2.ptintName();
/*
* The problem is that I don't know what to do if I want account1
* and account2 to belong both to client1. I tried Client client1 =
* new Client("George",account1); Client client1 = new
* Client("Oliver", account2); but got compilation error
*/
}
}
你知道我怎麼能解決這個問題?我應該怎麼做才能讓多個銀行賬戶與同一客戶關聯?
在此先感謝 喬治
這裏是輸出:'賬戶詳細信息:帳戶 '1' 帳戶詳細資料: 帳戶號碼:11223A餘額:1000個 帳戶細節的帳戶 '2': 帳戶號碼:11111A餘額:10000 ' – 2015-02-07 13:21:40
確定,謝謝,它工作正常,但我不明白爲什麼我們需要使用HashSet?爲什麼它只能用於Set? – George 2015-02-07 20:40:44
Set是更好的選擇。它不一定是HashSet。兩者之間的區別在於Set是一個接口,而HashSet是具體的類。您無法創建接口的實例。 – 2015-02-07 20:48:41