Vijaya Bhaskar wrote:What do you mean by identity here?
Something that makes an object
distinct from other objects; and
all objects in
Java have at least one form of identity - their
reference, which is similar to (and may actually be) a memory location - since no two objects can occupy the same space at the same time.
However, this is generally only useful to the JVM itself for managing memory. An application that you write that deals with people, for example, is likely to want some way of knowing when two different
Person objects refer to
the same person.
And
this form of identity doesn't just exist in Java. You usually need an identity to store a person in a database, or to make sure that a bank or ATM doesn't give money to the
wrong "John Smith".
And oddly enough, identifying
people is one of the oldest problems in Information Management, because most of the normal methods we use (name, address, date of birth, etc) are insufficient to
uniquely identify someone to a stranger or a computer system - although they're usually fine for social situations. And that's why our lives abound with customer IDs, account and social security numbers, and PINs.
Imagine I walked into a bank and said: "Hello, I'm John Smith. I'd like to take out £500 please". What's likely to be the response?
Assuming they don't laugh in my face, they might ask me all sorts of questions to try to whittle me down; but they'd still have no way of knowing whether or not I really was John Smith - I could simply be giving answers I read off a bank statement I found in a rubbish bin.
And the same (or similar) is true of many data structures - specifically
Sets and
Maps - you find in Java. They need to ensure that they don't contain "duplicate" objects (or keys); and the way they usually do that is with the
equals() and
hashCode() methods common to all Java objects - the latter only in the case of "hashed" datasets (which normally include '
Hash' somewhere in the class name).
And
that's why it's so important to implement these methods for practically every class you write.
HIH
Winston