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条)

报告相同问题?

悬赏问题

  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题