While doing some casual reading I came across an interesting quote by Scott Meyers
Anytime you find yourself writing
code of the form “if the object is of
type T1, then do something, but if
it’s of type T2, then do something
else,” slap yourself.
I was just wondering why Java has “instance of” operator when you could do the same thing by overridden methods? When is it actually used?
Sometimes you have to use objects whose behavior (e.g. source code) you do not control so you cannot always rely on object-oriented solutions to type-related matters. (Especially consider that authors of libraries cannot anticipate every use case you might have; of course, you could argue that extension and implementation provide workarounds but they require much more effort than direct type checking.)
The “instanceof” operator gives you a way to inspect the type of an object and act conditionally.