Well, in general, if you're iterating a collection and need to check the concrete type of the things in the collection, you're not using polymorphism in the first place. This is actually kind of anti-polylmorphism. Polymorphism would be iterating a collection and calling the "same" method on every object in the collection, but each object doing something different as a result of the method call. You should also not have an abstract class as the top of your inheritance hierarchy. That would be the job of an interface. Interfaces are for polymorphism, and abstract classes are a convenient spot for common code. So to make a long story short, try something like this:
Code:
public interface Foo {
void doSomething();
}
public abstract class AbstractFoo {
protected int toes; // because all Foos have some number of toes
public int getToes() { return toes; }
}
public class FiveToedFoo extends AbstractFoo implements Foo {
public FiveToedFoo() { this.toes = 5; }
public void doSomething() {
this.toes++; // Grow another toe
}
}
public class NineToedFoo extends AbstractFoo implements Foo {
private int ears = 2;
public NineToedFoo() { this.toes = 9; }
public void doSomething() {
this.toes--;
this.ears++; // Change a toe into an ear
}
}
See? So ultimately, I'd first look at coming up with a better design if you have the liberty to do so. This will greatly increase the modifiability, maintainability, and all those other -ilities, but most importantly, the simplicity of your code. Finding a graceful design early will make it much easier in the long run rather than trying to force something to work which is not so graceful to begin with.