简体   繁体   中英

How does inheritance work with for-each loops?

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?

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.

The first approach ( for (SubClass subClass : superClasses) ) cannot work as the compiler cannot ensure that there are only objects of tyoe SubClass in there.

In Java (without external libraries) it is not possible to preselect on the Class . Therefore the instanceof is the normal way to do this.

instanceof would work absolutely fine in this situation. But if you really do have reasons for not using it you could always give the superclass some variable, Boolean skipMe = true , and change that to false in the subclass if you wanted.

But I suggest using instanceof

我建议管理一个单独的List,如果可能的话,它只包含SubClass的实例。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM