I have a collection of animals (interface) which contains birds and cats (both also interfaces). I want to print out all the cats to the console and I am forbidden to use instanceof
(I did not make up this arbitrary restriction).
What is the correct way in OOP to solve this? getClass()
is not possible because I just have access to the API and it would not comply with OOP concepts. Another alternative would be the visitor pattern (I can change the API), but this would be just be a very convoluted way to effectively perform a type-check.
isCat()
. Only instances ofCat
will returntrue
instanceof
is general-purpose and overkill for most situations. If you only need to determine whether it is aCat
thenisCat()
is adequate. Better is a methodgetAnimalType()
which returns a string name; it doesn't wander intoinstanceof
territory, but ... meh.instanceof
orgetAnimalType
is effectively the same thing. When forbidding one (for homework matters) the other is automatically forbidden as well. The point is usually to force the student into using polymorphism. Usually ;)