Implementation advice (instanceof and interaction between subclasses)

I always see people railing on using instanceof as an example of poor OOP. I completely understand the argument, but the examples used are typically ones involving fairly shallow polymorphism (Animal.go(), animal.talk(), etc.)

When it comes to cases of interaction between the various subclasses, can instanceof be considered more acceptable? To continue the animal analogy, let's look at

Animal_A.eat(Animal_B);

If we say that dogs eat cats, cats eat rats, and rats eat dogs (they're huge), is there a good implementation that doesn't say

if(Animal_B instanceof Cat) Animal_B.die();?

I could use some kind of enum Type{CAT, RAT, DOG}, but that seems to just be duplicating instanceof in more lines of code.

That looks like exactly what I was thinking of - I didn't think to check if Java could overload with more specific sub classes, I figured it would only overload eat(Animal a);. I presume then that in your example, Cat_C.eat(Dog_D); would trigger die(); and return false? Thank you very much!

Yes, that works because the compiler 'knows' that a dog is a Dog and a cat is a Cat etc. If that dog, cat etc. would've been of class Animal the compiler would generate a call to the superclass method instead for all cases. Method overloading is compiler thing.

Yes, that works because the compiler 'knows' that a dog is a Dog and a cat is a Cat etc. If that dog, cat etc. would've been of class Animal the compiler would generate a call to the superclass method instead for all cases. Method overloading is compiler thing.

Cool; instead of doing an instanceof test we do a set presence test ... plus an entire set per class. ;-)

kind regards,

Jos

Indeed - from a performance standpoint it does not strike me as the most efficient solution. However, it could have merits - let's say there was a Animal.Hunt() method that searched out it's prey? The set could certainly be used elsewhere.

Cool; instead of doing an instanceof test we do a set presence test ... plus an entire set per class. ;-)

kind regards,

Jos

Actually, it's an entire Set per instance of a class...:)
Never do things by halves, that's what I say.

It's not actually intended as a serious answer, but more to highlight the inheritance here.
As in, the inheritance is an illusion largely due to the simplicity of the problem, hence the problem surrounding how to get animal A to eat animal B without doing instanceof or class comparisons. And the answer is to provide data (attributes) to Animal that allow it to identify predator/prey. Not to subclass Animal.