Java - override methods equals() and hashCode() in created classes.
Classes that have attributes non-static and have been used in collection, one should replace methods equals() and hashCode(). This will ensure that the returned results comparing two object are correctly.
If classes are not used in collection, this does not guarantee that that inherited method equals() from class Object ensures the correct operation of the. So and so must you do testing it, and in case of problems must overriding this two methods.
In some IDE of programing you can generate overwritten methodsequals() and hashCode() for created class. In Eclipse in class body press Shift+Alt+S and from menu context chose Generate hashCode() and equals()....
The best way is to see it on examples, below method generated by Eclipse.
Commented all and/or some methods whose been overwritten and see what was happens.
Created method equals() and hashCode() by Eclipse work well, but if you want to better know, how it works encode yourself.
The use of if (getClass() != obj.getClass()) instead of if (!(obj instanceof CDog)) has big meaning. In first case if you created class CSmallDog, whose inherited form class CDog and created two objects CSmallDog sdog and CDog dog and you do compare dog.equals(sdog); that you have result false. In second case when you use instanceof you see result true, what can cheat programer ;)
If you must use instanceof , then deleting checking block if (obj == null) that object is null, because in that case returned false without throw exception.
Example application instanceof in method equals().
If you find unintelligible text, write to me corrected words, please - lis.la(at)wp.pl