This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Java in General and the fly likes usage of getClass() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "usage of getClass()" Watch "usage of getClass()" New topic

usage of getClass()

Kasun Wixkramanayake
Ranch Hand

Joined: Feb 09, 2010
Posts: 74

i got the above code from effective java 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
Jeff Verdegan

Joined: Jan 03, 2004
Posts: 6109

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

Joined: Apr 06, 2010
Posts: 4344

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 - - that discusses this in more detail, and describes another approach.
I agree. Here's the link:
subject: usage of getClass()
Similar Threads
getClass and instanceOf
extending an instantiable class, adding an aspect and preserving the equals contract
Object and String
HashMap and HashSet