java 中equals方法的覆盖

(1)如果子类能够拥有自己的相等性概念,则对称性需求将强制采用getClass()方法进行检测

(2)如果由超类决定相等性概念,那么就可以使用instanceof 进行检测,这样就可以在不同的子类的对象之间进行比较

下面是一个覆盖equals()方法的比较好的proposal:

1) 显示参数命名为otherObject,稍后需要将它转化成叫做other的变量。

2)    检测this和otherObject是否属于同一个对象:if(this==otherObject)  return ture;  这条语句是条优化

3)  检测otherObject 是否为null,为null,则返回false if(otherObject==null) return false;

4)  比较this与otherObject是否属于同一个类,如果equals的语义在每个子类中有所改变,就使用getClass检测,

         if(getClass()!=otherObject.getClass())  return false;

      如果所有的子类都拥有统一的语义,就使用instanceof检测:

         if(!otherObject instanceof(ClassName))   return false;

5)  将otherObject转换成相应的类类型变量:

         ClassName other=(ClassName)otherObject;

6)  现在开始对所有需要比较的域进行比较了。使用==比较基本类型,使用equals比较对象域。如果所有都匹配,返回true。否则,返回false。

         return field1==other.field&&field2.equals(other.field2)&&...

如果要在子类中重新定义equals,就要在其中包含调用super.equals(other)。

Class Employee

{

double salary;

 string name;

 Date hireDay;

.........

public boolean equals(Object otherObject)

{

if (this==otherObject)  return false;

if(otherObject==null)   return false;

if(getClass()!=otherObject.getClass())  return false;

Employee other=(Employee)otherObject ;

return salary==other.salary&&name.equals(other.name)&&hireDay.equals(other.hireDay)

}

}

如果Manager是Employee的子类,且要比较两个Manager 是否相等,则还需要比较其奖金bonus,则这样写

Class Manager extends Employee

{

double bonus;

.....

double boolean equals(Object otherObject)

{

if(!super.eqauls(otherObject))   return false;

Manager other=(Manager)otherObject;

return bonus==other.bonus
}

}








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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值