简体   繁体   中英

The Object's equals Method?

Can anybody explain why the first code equates to false and the second to true? 在此处输入图片说明

在此处输入图片说明

All objects in Java start with the equals(Object) method, found in the base Object class. Your second example simply overrides this method, so that any time the equals(Object) method is called, the override implementation is used rather than the base implementation.

However, in your first example, you have added a new overload for the equals() method, with a parameter list different from the based Object.equals() method. This overload would be used any time you call it when both of these are true:

  1. The reference used to call the method has a compile-time type of Circle , and
  2. The parameter passed to the method has a compile-time type of Circle

The first condition is required so that the compiler can find the method in the first place. If the compile-time type of the target instance of the call is not Circle , then the equals(Circle) overload of the method will not even be considered as a possibility.

The second condition is required so that the compiler can identify the equals(Circle) overload as the one to be called. If the parameter being passed is not known at compile time to be Circle , then the compiler can't safely use the equals(Circle) method, and must instead choose the equals(Object) overload.

In your first example, the compile-time types of both the target instance for the method call, as well as the parameter passed to the method, is Object and not Circle . As such, the compiler has no safe way to call the equals(Circle) overload, and must instead call equals(Object) . And that overload, the base implementation, simply compares the references of the two objects, returning true only if they are identical (which in this case, being two different instances, obviously are not).

See also Overriding Object.equals VS Overloading it


As an aside: the second implementation is not quite right, because it assumes that the circle parameter passed in is always of type Circle . This is true in the degenerate code example in your question, but would not be generally true in a real-world program. A correct implementation of equals(Object) would check the type of the parameter first, and immediately return false if the type was not correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM