I was given the task to override the equals method in java, and I would like to know if the two examples I have provided will accomplish the same thing. If so, what are the differences between them.
public class Animal {
private int numLegs;
public Animal(int legs) {
numLegs = legs;
}
public boolean equals(Object other) {
if(other == null) return false;
if(getClass() != other.getClass()) return false;
return this.numLegs == ((Animal)other).numLegs;
}
public class Animal {
private int numLegs;
public Animal(int legs) {
numLegs = legs;
}
public boolean equals(Object other) {
//check if other is null first
if(other == null) return false;
//Check if other is an instance of Animal or not
if(!(other instanceof Animal)) return false;
//// typecast other to Animal so that we can compare data members
Animal other = (Animal) other;
return this.numLegs == other.numLegs;
}