I have gone through various articles, but I still do not know why instanceof
should not be used. Kindly let me know your thoughts.
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.
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.
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.
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.