Visitor pattern would be really good approach to consider in such situation. Let say, you are making a game that need to react differently for different object (Cat, Dog, Money, etc). So do this:
Make an interface IAnimal that has following definition:
interface IAnimal {
void visit(IAnimalVisitor visitor, Object param);
}
class Cat implements IAnimal {
void visit(IAnimalVisitor visitor, Object param) {
visitor.visit(this, param);
}
}
class Dog implements IAnimal {
void visit(IAnimalVisitor visitor, Object param) {
visitor.visit(this, param);
}
}
The IAnimalVisitor will contain one visit() method for each animal type defined. So it will be like:
interface IAnimalVisitor {
public void visit(Cat c, Object param);
public void visit(Dog c, Object param);
}
Then you could use put your logic to deal with cat and dog as per you want. For example:
class AnimalFeeder implements IAnimalVisitor {
public void visit(Cat c, Object param) {
c.feed(milk);
c.feed(cat_food);
}
public void visit(Dog d, Object param) {
d.feed(dog_food);
}
}
Then you can use above food feeding class to feed to you IAnimal array like this:
IAnimal[] animals = new IAnimal[] { new Cat(), new Dog(),
new Dog(), new Cat() };
IAnimalVisitor feeder = new AnimalFeeder();
for(IAnimal animal : animals) {
animal.visit(feeder, null);
}
You can achieve full freedom to deal with any level of hierarchy within classes. Just put the visit() for each animal class type within IAnimalVisitor.
obj.getClass()), but this doesn't necessarily save you from a poor design. What are you trying to accomplish?