0

I am using IntelliJ to auto generate the equals and hashCode function for following two classes. I found in the Dog class' equals method, it is doing

if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;

Should these two lines be omitted since they're in the parent class? I thought when calling super.equals(), those checks would happen in the parent class.

class Animal{
    String eye;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Animal animal = (Animal) o;
        return Objects.equals(eye, animal.eye);
    }

    @Override
    public int hashCode() {
        return Objects.hash(eye);
    }
}

class Dog extends Animal{
    String hair;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        if (!super.equals(o)) return false;
        Dog dog = (Dog) o;
        return Objects.equals(hair, dog.hair);
    }

    @Override
    public int hashCode() {
        return Objects.hash(super.hashCode(), hair);
    }
}
Makoto
  • 104,088
  • 27
  • 192
  • 230
michael
  • 397
  • 4
  • 12

1 Answers1

0

Yes, those lines could be omitted, since the call to super.equals will actually validate if the objects are the same instance, or if they're not the same type.

Just...be very careful about doing this at all with subclasses. It's not something that's commonly done for inherited types since equivalence isn't the same as an is-a relationship (for instance, a Dog is-an Animal, but not all Animals are Dogs, and defining equivalence for them all seems strange; two animals are not the same because their eyes are brown).

Makoto
  • 104,088
  • 27
  • 192
  • 230
  • Thx for reminding this, in my actual case base class "Animal" is an abstract class which can't be instantiated, have equals there because many fields are in base class and not want to include all fileds in all sub classes – michael Mar 15 '19 at 05:39