I have gone through various articles, but I still do not know why instanceof
should not be used. Kindly let me know your thoughts.

- 41,989
- 11
- 82
- 128

- 12,427
- 23
- 80
- 112
5 Answers
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)
.
-
Actually, Strategy is to decide what should be done according to a known criteria (like the type for example) but to dispatch unknown types on different code branches using polymorphism, the pattern used is [Visitor](http://en.wikipedia.org/wiki/Visitor_pattern) – Vincent Robert Sep 23 '10 at 09:19
-
IMO instanceof is better than polymorphism is special-case situations where a method makes sense in only one subclass, and the parent class and/or other subclasses would be forced to implement stub methods that are meaningless in their context. Even then, one should try to call the special-case method from an inherited method, but if that is cumbersome then using instanceof is perfectly justified. – Barry Fruitman Jun 10 '12 at 03:15
One good use-case would be checking for marker interfaces like RandomAccess.

- 257,207
- 101
- 511
- 656
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.

- 36,122
- 25
- 118
- 131
When you know the object being passed then you need not use it. If there is any ambiguity involved (like two classes implementing the same interface) then it is advised to use instanceof
before proceeding further.

- 1,916
- 15
- 23
Using instanceof when overriding Object's equals method is necessary, seeing as two objects cannot be equal if they are of different types. I've rarely come accross another situation where instanceof is required - perhaps if downcasting is required but a ClassCastException may be thrown.

- 5,360
- 4
- 38
- 47