i got the above code from effective java book.it is used to preserve the Transitivity.why this code use getclass instead of instance of .Can you explain it for me.i couldn't understand the reason for it
If you only want instances of that specific class to be able to be equal to each other, you use getClass().
If you want an instance of any class a subtree in the type hierarchy to be able to be equal to an instance of any other class in that same subtree, you use instanceof. For example, the documentation for java.util.List says that a List is equal to another object if that other object is also a List and has the same number of elements and each corresponding pair of elements in order is equal. So an ArrayList can be equal to a LinkedList. To abide by this contract, every List implementation must use instanceof List in its equals() method.
Well, this is the classic example. Let's say we extend Point to ColourPoint, so we add a colour attribute. And we override equals() in ColourPoint to use this as well. Now imagine we're using instanceof.
Now we've broken the symmetric part of the equals() contract:
It's not all lovely if we just use getClass(), though, because that's stricter than we sometimes want - see Jeff's example about List. You might find the following article interesting - http://www.artima.com/lejava/articles/equality.html - that discusses this in more detail, and describes another approach.
All of the world's problems can be solved in a garden - Geoff Lawton. Tiny ad:
RavenDB is an Open Source NoSQL Database that’s fully transactional (ACID) across your database