How does inheritance work with for-each loops?

foreach, inheritance, java

Solution

Well you could write a helper method to hide the `instanceof` test... Guava has a method like this, for example, in `Iterables.filter`, which you could use like this:

for (SubClass subclass : Iterables.filter(superclasses, SubClass.class)) {
    ...
}

It's only moving the `instanceof` check though really - it's not getting rid of it. Fundamentally you need that check, because something's got to do the filtering.

Problem

How does inheritance work in relation to a for-each loop? Imagine I have two classes: `SubClass` and `SuperClass`, and I have the following `ArrayList`. ``` /** * Containes both SuperClass and SubClass instances. */ ArrayList<SuperClass> superClasses = new ArrayList<SuperClass>(); ``` Is it possible to iterate over `superClasses` in such a way as to only select `subClasses`. The following: ``` for(SubClass subClass : superClasses){ // Do Foo } ``` does not do this. The following is the only thing that I could get to work: ``` for(SuperClass superClass : superClasses){ if(superClass instanceof SubClass){ // Do Foo } } ``` However I do not want to use `instanceof` unless absolutely necessary, as I keep reading everywhere (StackOverflow, Oracle Tutorials etc) that one can almost always find a better solution that increases encapsulation. Is there a more elegant way of doing this?

Original source

Related problems