-1

我有 2 个相互扩展的类。我有一个调用类 Address.Java 以从类中获取城市和州的 mutator 方法。但是 Bank.java 类给我带来了问题。给我带来问题的具体方法是

public void setBankAddress(String aCity,String aState)(代码如下)我不知道这是否有意义{

}

银行.Java

public class Bank
{
     private String bankName;
     private int bankID;
     private Address bankAddress;

     public Bank()
     {
         bankName = "?";
         bankID = 0;
         bankAddress = new Address();
     }   

     public String getBankName()
     {
         return bankName;
     }

     public int getBankID()
     {
         return bankID;
     }

     public Address getBankAddress()
     {
         return bankAddress;
     }

     public void setBankName(String aBankName)
     {
         bankName = aBankName;
     }

     public void setBankID(int aBankID)
     {
         bankID = aBankID;
     }

     public void setBankAddress(String aCity, String aState)
     {

     }

     public String toString()
     {
         return "\nBank name:\t\t" + bankName + "\nBank ID:\t\t" + bankID + "\nBank    Address:\t\t" + bankAddress + "\n\n";
      }

}

地址。爪哇

public class Address
{
    private String city;
    private String state;

    public Address()
    {
    city = "?";
    state = "?";
    }

    public String getCity()
    {
    return city;
    }

    public String getState()
    {
    return state;
    }

    public void setCity(String aCity)
    {
    city = aCity;
    }

    public void setState(String aState)
    {
    state = aState;
    }

    public String toString()
    {
    return city + "," + state;
    }

}
4

1 回答 1

2

你只是不知道如何调用对象的方法吗?

public void setBankAddress(String aCity, String aState)
{
    bankAddress.setCity(aCity);
    bankAddress.setState(aState);
}

bankAddress已在构造函数中初始化,因此您可以安全地调用这些方法。

但是,在此类方法之外执行此操作并传递整个对象本身通常是一种好习惯

Address someAddress = new Address();
someAddress.setCity(aCity);
someAddress.setState(aState);

Bank bank = new Bank();
bank.setBankAddress(someAddress);
...
public void setBankAddress(Address aBankAddress) {
    bankAddress = aBankAddress;
} 
于 2013-09-05T18:16:04.903 回答