开发者社区> 问答> 正文

java的equals方法重写中的小问题

     public boolean equals(Object otherObject)
   {
      // a quick test to see if the objects are identical
      if (this == otherObject) return true;

      // must return false if the explicit parameter is null
      if (otherObject == null) return false;

      // if the classes don't match, they can't be equal**
            //如果equals语义在子类中有所改变,就是子类的equals和父类的equals在概念上是不同的,那就用getClass来比较类
      if (getClass() != otherObject.getClass()) return false;
            //如果equals语义在子类中并没有发生改变,和父类是一样的,那么就用instanceof来比较类是否相同
            if(!(otherObject instanceof ClassName)) return false;**
      // now we know otherObject is a non-null Employee
      Employee other = (Employee) otherObject;

      // test whether the fields have identical values
      return name.equals(other.name) && salary == other.salary && hireDay.equals(other.hireDay);
   }

为什么子类中的语义不同就用getClass而相同就用instanceof?我知道二者的区别,而且我觉得这个instanceof应该有点问题吧,就是比如a是父类,b是子类,且这时候子类的equals语义没有发生变化,那么a.equals(b)和b.equals(a)的结果就不一样了吧,因为子类instanceof父类是true,而父类instanceof子类就是false——这就不满足equals定义中的对称性。

展开
收起
蛮大人123 2016-03-18 18:10:00 2076 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    子类和父类的比较到不了instanceof那里。

    2019-07-17 19:07:01
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载