• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
Bartenders:
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

usage of getClass()  RSS feed

 
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
 
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.
 
Bartender
Posts: 4568
9
  • 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
Boost this thread!