qq_23908539 2015-09-12 07:31 采纳率: 87.5%
浏览 1917
已采纳

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定义中的对称性。
大神求解

  • 写回答

4条回答 默认 最新

  • JonsonJiao 2015-09-13 02:12
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格