Can anybody explain why the first code equates to false and the second to true?

- 68,759
- 7
- 102
- 136

- 1
- 1
-
1please add a language tag, and type out your code – peer Mar 25 '20 at 00:13
-
1Because nobody calls `Circle.equals(Circle circle)`. Don't post pictures of text here. Post the text. Complete waste of your time and our bandwidth. – user207421 Mar 25 '20 at 01:28
1 Answers
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:
- The reference used to call the method has a compile-time type of
Circle
, and - 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.

- 68,759
- 7
- 102
- 136