Java - equals method in base class and in subclasses

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()
}

No, it's not possible to conform to the equals contract when introducing new fields which are relevant to the equals method. See "Effective Java" by Joshua Bloch for more information.

Edit:

I don't have the book at hand right now, but I think it's ok if the base class is abstract/ cannot be instantiated.


Take a look at "Implementing equals() To Allow Mixed-Type Comparison" from Angelika Langer .

Here is a brief explanation of some problems and a possible solution:

The equals contract says (amongst others):

It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

That means you might get problems if your sub class is introducing new fields and you're comparing an object of the base class (or another sub class that doesn't override equals) to an object of this sub class.

Do NOT do the following:

class BaseClass {
    private int field1 = 0;

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof BaseClass) {
            return field1 == ((BaseClass) obj).field1;
        }
        return false;
    }
}

class BadSubClass extends BaseClass {
    private int field2 = 0;

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof BadSubClass) {
            return super.equals(obj) 
                    && field2 == ((BadSubClass) obj).field2;
        }
        return false;
    }
}

because you get

BaseClass baseClass = new BaseClass();
BadSubClass subClass = new BadSubClass();

System.out.println(baseClass.equals(subClass)); // prints 'true'
System.out.println(subClass.equals(baseClass)); // prints 'false'

A possible solution:

Replace the instanceof-check with a class comparison:

obj != null && obj.getClass() == getClass()

With this solution an object of BaseClass will never be equal to an object of any subclass.

If you create another SubClass without an @Override of the equals method, two SubClass-objects can be equal to each other (if the BaseClass.equals check decides so) out of the box, but a SubClass-object will never be equal to a BaseClass-object.

A good implementation could be as follows:

class BaseClass {
    private int field1 = 0;

    @Override
    public boolean equals(Object obj) {
        if (obj != null && obj.getClass() == getClass()) {
            return field1 == ((BaseClass) obj).field1;
        }
        return false;
    }
}

class GoodSubClass extends BaseClass {
    private int field2 = 0;

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof GoodSubClass) {
            return super.equals(obj) && field2 == ((GoodSubClass) obj).field2;
        }
        return false;
    }
}

Please refer to the article mentioned above for more advanced problems and their solutions.

Tags:

Java

Equals