下面是一个根据业务键实现equals()与hashCode()的例子。实际中需要根据实际的需求,决定如何利用相关的业务键来组合以重写这两个方法。
public class Cat
{
private String name;
private String birthday;
public Cat()
{
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void setBirthday(String birthday)
{
this.birthday = birthday;
}
public String getBirthday()
{
return birthday;
}
//重写equals方法
public boolean equals(Object other)
{
if(this == other)
{
//如果引用地址相同,即引用的是同一个对象,就返回true
return true;
}
//如果other不是Cat类的实例,返回false
if(!(other instanceOf Cat))
{
return false;
}
final Cat cat = (Cat)other;
//name值不同,返回false
if(!getName().equals(cat.getName())
return false;
//birthday值不同,返回false
if(!getBirthday().equals(cat.getBirthday()))
return false;
return true;
}
//重写hashCode()方法
public int hashCode()
{
int result = getName().hashCode();
result = 29 * result + getBirthday().hashCode();
return result;
}
}
重写父类方法的原则:可以重写方法的实现内容,成员的存取权限(只能扩大,不能缩小),或是成员的返回值类型(但此时子类的返回值类型必须是父类返回值类型的子类型)。