0

I was making some tests with the java equals method and I figured out that if my parameter is not of the generic type Object the test won’t pass, even if the two objects I create are of that type. Let’s say I want to check if an object is an animal, what I tried to do is writing down:

 public boolean equals(Animal other) {
 *some code*
}

And then I create a test for that method to compare the animals. But if I do that the test will fail, on the other side, if I write down:

public boolean equals(Object other) {
 *some code*
}

and then test it, the test will pass. I understand that’s useless declaring the object of the desired type and try to test it but I don’t get why it doesn’t work in a good weather test case.

Jasmine
  • 117
  • 10

2 Answers2

4

It is simple, Object class equals method signature is this

public boolean equals(Object obj)

But if you write equals method with Animal parameter then it will not be the Overridden equals method from object class. and when you try to compare objects by using .equals() Object class equals will be invoked

For this reason and to make it clear it is always recommended to use @Override annotation

Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
2

The equals method is part of the base Object class in Java and the only way to make benefit of it is to override it. To override it you need to stick to the same signature which will tell any libraries using equals to invoke your method instead of the base one.

Your above code is doing an overloading which is a totally different method to the Java compiler.

Eslam Nawara
  • 645
  • 3
  • 8