天天看點

不可變類練習

10.23

不可變類練習

public final class Address
{
  private final String detail;
  private final String postCode;  //在構造方法裡初始化兩個執行個體屬性
  public Address()
  {
    this.detail = "";
    this.postCode = ""; }
  public Address(String detail , String postCode)
  {
    this.detail = detail;
    this.postCode = postCode;
  }
  //僅為兩個執行個體屬性提供getter方法
  public String getDetail()
  {
     return this.detail;
  } public String getPostCode()
  {
     return this.postCode;
  }
  //重寫equals方法,判斷兩個對象是否相等。
  public boolean equals(Object obj)
  {
    if (obj instanceof Address)
    {
      Address ad = (Address)obj;
      if (this.getDetail().equals(ad.getDetail()) && this.getPostCode().equals(ad.getPostCode()))
      {
        return true;
      }
    }
    return false;
  }
  public int hashCode()
  {
    return detail.hashCode() + postCode.hashCode();
  }
}