When should and shouldn't instanceof be used?

I find a need to use instanceof hints at bad design. It's a sure sign that a big, complex switch-style construct will follow. Most other times I see it used, we should use polymorphism rather than instanceof. See the Strategy pattern. (relevant examples of use)

The only time I find I need to use it is when implementing equals(Object o).


One good use-case would be checking for marker interfaces like RandomAccess.


Casting from a base type to a derived type is a bad thing. If you use instandof that way, it's considered bad design because hard to maintain and read. See http://www.javapractices.com/topic/TopicAction.do?Id=31.

Using instanceof for equals() because you have an object that should be your type, that's good practice.

Tags:

Java