问题描述
我使用 java equals 方法进行了一些测试,我发现如果我的参数不是泛型类型 Object,即使我创建的两个对象属于该类型,测试也不会通过.假设我想检查一个物体是否是动物,我试图做的是写下:
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.
推荐答案
很简单,Object类equals
方法签名就是这个
It is simple, Object class equals
method signature is this
public boolean equals(Object obj)
但是,如果您使用 Animal
参数编写 equals
方法,那么它将不是来自对象类的 Overridden
equals 方法.当您尝试使用 .equals()
比较对象时,将调用对象类 equals
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
出于这个原因,为了清楚起见,始终建议使用 @Override
注释
For this reason and to make it clear it is always recommended to use @Override
annotation
这篇关于为什么我们需要为 equals 方法提供一个 Object 参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!