• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

InstanceOf() Vs getClass()

 
Ranch Hand
Posts: 153
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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()

 
Marshal
Posts: 79261
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Sheriff
Posts: 22784
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic