【Core Java Volume1】重写equals,hashCode,toString方法
原创
©著作权归作者所有:来自51CTO博客作者wx637b060b079f7的原创作品,请联系作者获取转载授权,否则将追究法律责任
1 重写equals()方法:
例:重写父类Employee3的equals方法
//重写equals
//1 显示命名参数otherObject,稍后转化为other
public boolean equals(Object otherObject){
//2 检测this与 otherObject 是否引用同一个对象
if(this == otherObject) return true;
//3 检测otherObject 是否为null
if(otherObject == null) return false;
// 4 比较this与 sotherObject 是否为同一个类
if(getClass()!= otherObject.getClass())
return false;
//5 转化
Employee3 other =(Employee3)otherObject;
//比较,基本类型的就用==比较
return Objects.equals(name, other.name) && salary ==other.salary
&& Objects.equals(hireDate, other.hireDate);
}
子类Manager3继承
Employee3,其重写的equals()方法如下:
<span > </span>public boolean equals(Object otherObject){
if(! super.equals(otherObject))
return false;
Manager3 other =(Manager3)otherObject;
return bonus == other.bonus;
}
2 重写HashCode()方法:
父类:
//重写hashCode
public int hashCode(){
return Objects.hash(name,salary,hireDate);
}
子类:
<span > </span>public int hashCode(){
return super.hashCode() + 17*new Double(bonus).hashCode();
}
3
父类:
//重写toString
public String toString(){
return getClass().getName()+"[name="+name+",salary="+salary+",hireDate="+hireDate+"]";
}
子类:
public String toString(){
return super.toString()+"[bonus="+bonus+"]";
}