aspose file tools*
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "usage of getClass()" Watch "usage of getClass()" New topic
Author

usage of getClass()

Kasun Wixkramanayake
Ranch Hand

Joined: Feb 09, 2010
Posts: 74

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
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

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
Bartender

Joined: Apr 06, 2010
Posts: 4363
    
    8

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: usage of getClass()