aspose file tools*
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
Author

InstanceOf() Vs getClass()

Nilesh Raje
Ranch Hand

Joined: Aug 02, 2005
Posts: 153
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

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

Joined: Oct 27, 2005
Posts: 19761
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
wood burning stoves
 
subject: InstanceOf() Vs getClass()