I am trying to understand 'Overriding equals()' topic from K&B chapter 7. But I am not able to understand it properly. Can anyone please suggest me some other link which can explain the same in simple language
Hi Aparna , What I can suggest you that,you just take one example of overriding equals() and then try to understand it .If you are not clear then ask for the explanation on those point you are not clear. regards, Subhasish [ November 18, 2008: Message edited by: subhasish nag ]
The equals() method is the way to determine when two objects are considered equals based on real caracteristics that makes sense to the class writer.
When you compare objects, if they dont override equals, how can Java know if they are equal? Java can't guess it.
If you don't provide a way for Java to know if they are equal, Java will compare its references, and references are barely "memory address", which usually doesnt make sense in a real world. Thats what the Object equals() method do, compare the reference of two objects with "==".
For instance, the String equals() method was overriden, and for the String's Class writer, it makes sense to say that two String objects are equals if they have the same character sequence.
If you write a Client class, and for your business logic two Client's are equals when they have the same account number, you can override the equals() method in your class and return true when the objects account number are the same, which means "For the Client class, it makes sense to say that two instance of Clients objects are equals when they have the same account number".