[英]How can I associate Class A with Class B, and the return a reference to class B from a method located in class A?
A級
public class Customer {
// Add instance varables
private String lName;
private String fName;
private String address;
private String zip;
// A constructor that initializes the last name, first name, address, and zip code.
public Customer(String lN, String fN, String addr, String zi) {
lName = lN;
fName = fN;
address = addr;
zip = zi;
}
// setAccount(Account a) - Sets the Account for this customer
}
// getAccount() - Returns a reference to the Account object associated with this customer
public Account getAccount(){
return();
}
}
我不知道如何從另一個類中“引用”一個對象。 我無法創建該對象,因為我希望所有東西都是通用的,並且能夠在以后創建,並使兩個類正確地相互關聯。
B級
public class Account {
// Add instance variables
private String accountNumber;
private double balance;
private Customer customer;
// A constructor that initializes the account number and Customer, and sets the blance to zero.
public Account(String aN, Customer c) {
accountNumber = aN;
balance = 0.00;
customer = c;
}
所以我無法理解如何在A類中創建設置帳戶和獲取帳戶方法
假設 Customer 有一個 Account,從 Customer 添加:
private Account account;
public void setAccount( Account account ){ this.account = account; }
public Account getAccount( ){ return account; }
並從帳戶中刪除與客戶相關的所有內容。 然后您可以使用來自 A(客戶)的 getAccount() 返回對 B(帳戶)的引用
如果您想要另一種方式(帳戶有客戶):
public class Account {
// Add instance variables
private String accountNumber;
private double balance;
private Customer customer;
public Account(String aN) {
accountNumber = aN;
balance = 0.00;
}
public Customer getCustomer(){ return customer;}
public void setCustomer(Customer customer){ this.customer = customer;}
}
...然后您可以使用 A(帳戶)中的 getCustomer() 來獲取對 B(客戶)的引用
哪個類引用另一個類完全取決於您的解決方案的設計。
這是一個雞和母雞的問題。 必須首先實例化一個對象。 它是哪一種並不重要,但必須是它。 如果客戶和帳戶永久綁定在一起,我強烈建議將字段設為“最終”。
class Customer {
private final Account account;
public Customer() {
account = new Account(this);
}
public Account getAccount() {
return account;
}
}
class Account {
private final Customer customer;
public Account(Customer customer) {
this.customer = customer;
}
public Customer getCustomer() {
return customer;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.