Java 如何将类A与类B关联,并从位于类A中的方法返回对类B的引用?

Java 如何将类A与类B关联,并从位于类A中的方法返回对类B的引用?,java,class,associations,Java,Class,Associations,甲级 } 我不知道如何从另一个类中“引用”对象。我无法创建该对象,因为我希望所有内容都是通用的,并且能够在以后创建,并使这两个类正确地相互关联 B类 public class Customer { // Add instance varables private String lName; private String fName; private String address; private String zip; // A constructor that initial

甲级

}

我不知道如何从另一个类中“引用”对象。我无法创建该对象,因为我希望所有内容都是通用的,并且能够在以后创建,并使这两个类正确地相互关联

B类

    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();
}

因此,我无法理解如何在A类中创建set account和get account方法

假设客户只有一个帐户,则从客户添加:

    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(客户)使用getAccount()返回对B(帐户)的引用

如果您想要另一种方式(客户有客户):

…然后可以从A(帐户)使用getCustomer()获取对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;}

}

您正在尝试在此处创建循环引用;请记住,
客户
可能有多个
帐户
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;}

}
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;
    }

}