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