secret
Last active

  • Download Gist
gistfile1.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
public class Animal {
@Override
public final boolean equals(Object other) {
// take care of the boilerplate stuff and ensure that "other" is of the same exact class as this
if (other == null) return false;
if (other == this) return true;
if (other.getClass() != this.getClass()) return false;
Animal otherAnimal = (Animal) other;
return animalFieldsAreEqual(otherAnimal);
}
protected boolean animalFieldsAreEqual(Animal other) {
return other.legCount = legCount; // or whatever
}
@Override
public int hashCode() {
// remember to override this, too!
}
...
}
 
public class Dog extends Animal {
@Override
protected boolean animalFieldsAreEqual(Animal other) {
if (!super.animalFieldsAreEqual(other)) return false;
Dog otherDog = (Dog) other; // guaranteed to work due to the class checking in equals
return otherDog.breed = breed; // or whatever
}
...
@Override
public int hashCode() {
// remember to override this, too!
int hash = super.hashCode();
hash = ...
return hash;
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.