Why do we need an Object parameter for equals method? [duplicate]

佐手、 提交于 2021-02-05 09:20:08

问题


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.


回答1:


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




回答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.



来源:https://stackoverflow.com/questions/53926475/why-do-we-need-an-object-parameter-for-equals-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!