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

问题描述 投票:0回答:2

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类中创建设置帐户并获取帐户方法

java class associations
2个回答
0
投票

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

private Account account;

public void setAccount( Account account ){ this.account = account; }

public Account getAccount(  ){ return account; }

并从帐户中删除与客户相关的所有内容。然后,您可以使用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;}

}

...然后,您可以使用getCustomer()获取对B(客户)的引用

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


0
投票

这是鸡和鸡的问题。必须先实例化一个对象。它是哪一个都没有关系,但必须是它。如果客户和帐户永久绑定在一起,我强烈建议将字段设置为“最终”。

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

}
© www.soinside.com 2019 - 2024. All rights reserved.