• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

usage of getClass()

 
Kasun Wixkramanayake
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4567
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic