File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes InstanceOf() Vs getClass() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "InstanceOf() Vs getClass()" Watch "InstanceOf() Vs getClass()" New topic

InstanceOf() Vs getClass()

Nilesh Raje
Ranch Hand

Joined: Aug 02, 2005
Posts: 153

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

Joined: Oct 13, 2005
Posts: 46389
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

Joined: Oct 27, 2005
Posts: 20276

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.

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: InstanceOf() Vs getClass()
jQuery in Action, 3rd edition