Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

regarding instanceof operator

 
Vasudhaiv Naresh
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I had just seen somewhere that using the instanceof operator is not advised. I'd like to know the reason why it shouldn't be used.
Regards,
Naresh
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's a typical use of instanceof that's problematic.If this is an open-ended hierarchy, then as more classes extend A, you'll have to find the code like method f throughout your program and add more cases. A better solution in this case would be if there were a polymorphic method doF() that you could invoke:This doesn't mean that you should never use instanceof. There are places where it's unavoidable.
 
Henrique Sousa
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are times when you just cannot avoid using instanceof, like when you override Object.equals or Comparable.compareTo. Sometimes the abstraction and contract just won't let you be specific when taking a parameter.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic