This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Overriding the Equals Method  RSS feed

 
Mohammed Azeem
Ranch Hand
Posts: 56
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good Afternoon Everyone,

I'm studying for the OCA (using Mala Gupta's excellent book)

I understand that the default equals() method simply compares the heap addresses contained in object reference variables x and y:

i.e  (x = = y) is true) if x and y refer refer to the same object and as such, the internal state of these objects will also be identical (the "objects" are one and the same) meaning they will be truly equal.

However, two different objects referred to by x and z may have identical internal states but the default equals() will return false. So if we want to compare for equality by judging the internal states of the objects, then the equals method must be overridden.

This much I understand. I also understand the JAVA API contract for the equals method.

Sooo much I understand... He. he..  LOL.

But I don't understand why an overridden equals method that does not accept (Object o) as parameter will be incorrect:

This is the context (from Mrs. Gupta's book)


the code returns false (when we want it to be true) because the parameter passed to the overrridden equals method is not (Object anObject

Miss Gupta offers this explanation:


An ArrayList uses the method equals to compare two objects. Because the class BankAccount didn't follow the rules for correctly defining (overrriding) the method equals, ArrayList uses the default equals from the base class Object, which compares object references. Because the code didn't add b2 to the list, it prints false.




So my question is:

boolean equals(BankAccount anObject) returns false
boolean equals(Object anObject) returns true

Why??


 
Paweł Baczyński
Bartender
Posts: 2054
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In BankAccount the method equals is not overriden. It is overloaded.
You can check this by adding @Override annotation to it and trying to compile.

Also, equals in Object is public so if the method of BankAccount was overriding it, you would get a compile error anyway because of weaker access privileges.

Besause BankAccount#equals(BankAccount) doesn't override Object#equals(Object) the latter one is called by the ArrayList.
 
Mohammed Azeem
Ranch Hand
Posts: 56
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ha..ha.. Silly me.

So simple.

Thank you very much Pavel.

Onwards and upwards...
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!