处理多样性关系
舒适的家庭生活会导致一个或更多 “小人儿” 降临到这个家庭。但是,在增加小孩到家庭中之前,先确保 Person 真正有地方可住。给他们一个工作场所,或者还有一个很好的夏日度假屋。一个 Address 类型应该可以解决所有这三个地方。
清单 1. 添加一个 Address 类型到 Person 类中
package com.tedneward.model;
public class Address
{
public Address()
{
}
public Address(String street, String city, String state, String zip)
{
this.street = street; this.city = city;
this.state = state; this.zip = zip;
}
public String toString()
{
return "[Address: " +
"street=" + street + " " +
"city=" + city + " " +
"state=" + state + " " +
"zip=" + zip + "]";
}
public int hashCode()
{
return street.hashCode() & city.hashCode() &
state.hashCode() & zip.hashCode();
}
public boolean equals(Object obj)
{
if (obj == this)
return this;
if (obj instanceof Address)
{
Address rhs = (Address)obj;
return (this.street.equals(rhs.street) &&
this.city.equals(rhs.city) &&
this.state.equals(rhs.state) &&
this.zip.equals(rhs.zip));
}
else
return false;
}
public String getStreet() { return this.street; }
public void setStreet(String value) { this.street = value; }
public String getCity() { return this.city; }
public void setCity(String value) { this.city = value; }
public String getState() { return this.state; }
public void setState(String value) { this.state = value; }
public String getZip() { return this.zip; }
public void setZip(String value) { this.zip = value; }
private String street;
private String city;
private String state;
private String zip;
}