Java - equals method in base class and in subclasses

前端 未结 8 985
自闭症患者
自闭症患者 2020-11-30 06:45

I have a simple base class, which is later extended by many separate classes, which potentially introduce new fields, but not necessarily. I defined an equals method in the

8条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 07:33

    While the following doesn't handle every case, I've found it to be quite practical. I've used this many times when I have both a SuperClass and a SubClass in play. I don't want to inter-compare them, but I also don't want to re-implement all of SuperClass equals() for SubClass. It handles:

    • a.equals(b) == b.equals(a)
    • Does not duplicate field comparison code
    • Easily generalized for any subclass depth
    • Subclass.equals(SuperClass) == false
    • Superclass.equals(SubClass) == false

    Code example

    // implement both strict and asymmetric equality
    class SuperClass {
       public int f1;
       public boolean looseEquals(Object o) {
          if (!(o instanceof SuperClass)) return false;
          SuperClass other = (SuperClass)o;
          return f1 == other.f1;
       }
       @Override public boolean equals(Object o) {
          return looseEquals(o) && this.getClass() == o.getClass();
       }
    }
    class SubClass extends SuperClass {
       public int f2;
       @Override public boolean looseEquals(Object o) {
          if (!super.looseEquals(o)) return false;
          if (!(o instanceof SubClass)) return false;
          SubClass other = (SubClass)o;
          return f2 == other.f2;
       }
       // no need to override equals()
    }
    

提交回复
热议问题