Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

InstanceOf() Vs getClass()

 
Nilesh Raje
Ranch Hand
Posts: 153
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,



when we overide the equals method in a class for a given object then we use getClass to check the class type of the given object.

InstanceOF is also a option here but I know that instanceOf is a bad/inefficient and poor programming as I had read it somewhere.

Can any one justify why instanceOf is inefficient then getClass. Also would like to know details of InstanceOf() Vs getClass()

 
Campbell Ritchie
Sheriff
Pie
Posts: 47258
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do a google search for "Angelika Langer Java equals method" or find the appropriate chapter in Joshua Bloch's Effective Java, 1st edition or 2nd edition. Those sources both explain the difference.

And no capital letters in instanceof please.

For instanceOf() (presumably not InstanceOf()) you should look in the Java API documentation (I don't have a link to hand just at the moment, sorry) then INDEX then I, and you can find where that method comes from.
 
Rob Spoor
Sheriff
Pie
Posts: 20380
46
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
instanceof potentially breaks the symmetry-part of the equals contract; it may lead to situations where a.equals(b) but !b.equals(a), something that is not allowed.

With getClass(), you limit your design because instances of a class can never be equal to instances of its sub classes.


It's a trade-off where you will need to decide which is more important. I usually use getClass(), unless I make the class or equals method final.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic