我对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