【问题标题】: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 类与 B 类关联,并从 A 类中的方法返回对 B 类的引用?
【发布时间】:2020-02-06 20:52:41
【问题描述】:

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类中创建set account和get account方法

【问题讨论】:

  • 您正在尝试在此处创建循环引用;记住Customer 可能有多个Account

标签: java class associations


【解决方案1】:

这是一个鸡与鸡的问题。必须首先实例化一个对象。它是哪一种并不重要,但必须是它。如果客户和帐户永久相互绑定,我强烈建议将字段设置为“最终”。

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

}

【讨论】:

    【解决方案2】:

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

    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(客户)的引用

    哪个类引用另一个完全取决于您的解决方案的设计。

    【讨论】:

      猜你喜欢
      • 2013-06-12
      • 2014-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-03
      • 2021-11-14
      • 1970-01-01
      相关资源
      最近更新 更多