首页 > 编程语言 >【Core Java Volume1】重写equals,hashCode,toString方法

【Core Java Volume1】重写equals,hashCode,toString方法

时间:2022-11-22 12:39:19浏览次数:120  
标签:Core return otherObject equals hashCode other Java 重写


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+"]";
}




标签:Core,return,otherObject,equals,hashCode,other,Java,重写
From: https://blog.51cto.com/u_15886477/5877669

相关文章