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

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 style="white-space:pre">	</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 style="white-space:pre">	</span>public int hashCode(){
		return super.hashCode() + 17*new Double(bonus).hashCode();
	}


3 重写toString()方法:返回对象值的字符串,最好通过调用getClass().getName()获得类名的字符串


父类:

//重写toString
	public String toString(){
		return getClass().getName()+"[name="+name+",salary="+salary+",hireDate="+hireDate+"]";
	}
子类:

	public String toString(){
		return super.toString()+"[bonus="+bonus+"]";
	}












  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值