Java - equals method in base class and in subclasses

前端 未结 8 951
自闭症患者
自闭症患者 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:30

    I guess, That's perfect to provide the equals(Object obj) and hashCode() method implementation in super class as Java did. We all know that Java provide the hashCode() and equals(Object obj) method implementation in the base class java.lang.Object, and when ever required we override them in our class.

    0 讨论(0)
  • 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()
    }
    
    0 讨论(0)
提交回复
热议问题