Is using the instanceof
keyword against the essence of object oriented programming
?
I mean is it a bad programming practice?
I read somewhere that us
It's discouraged because people might use it to do something like this:
if( myAnimal instanceof Dog )
((Dog)myAnimal).bark();
else( myAnimal instanceof Cat )
((Cat)myAnimal).meow();
Instead, Animal
should have a speak()
method which Dog
and Cat
inherit. In proper OOP with polymorphism and dynamic binding, you would then simply do
myAnimal.speak();
However, there are some instances in which you must use instanceof
to determine the specific type of an object. Perhaps you have a list of Animals
in your house and the only ones you want to take out for a walk()
are the Dog
s. In that case you would iterate through your list and only walk()
the dogs.