3

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;
    }
elnamy
  • 27
  • 4

3 Answers3

5

They are not the same.

For the first implementation, you can only return true if both of the compared instances belong to the same class (for example, if both are Cat instances, assuming Cat extends Animal).

For the second implementation, you can compare a Cat to a Dog and still get true, since both are instances of Animal and have the same number of legs.

They will behave the same if there are no sub-classes of the Animal class, since in that case, if other instanceof Animal is true,getClass() == other.getClass()is alsotrue`.

P.S., the second snippet has a typo, since you are re-declaring the other variable:

Animal other = (Animal) other;
return this.numLegs == other.numLegs;

You probably meant to use a different variable name.

Eran
  • 387,369
  • 54
  • 702
  • 768
2

They don't do the same thing with subclasses of Animal; say if you have a class Dog extending Animal, and an instance dog, calling animal.equals(dog) will return false with the first version, and true with the second.

Maurice Perry
  • 9,261
  • 2
  • 12
  • 24
1

They are different:

case 1: This check will always return true if the instance belongs to same class like Cow extends Animal and Cat extends Animal.

Case 2: In this case, if both are the instance of Animal and have same number of legs -- return true.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
Sai prateek
  • 11,842
  • 9
  • 51
  • 66