Search code examples
javagenericsinheritancetyped

Java method that takes only objects that inherit from super class


I would like to have a method in a Java class that will allow me to pass only objects that inherit from super class, f.e.:

I have container super class Div:

package org.gwtbootstrap3.client.ui.html;
    public class Div extends ComplexWidget {
        public Div() {
            setElement(Document.get().createDivElement());
        }
    }

I would like to use Div class and its children in the NRowsXNColumns class:

public class NRowsXNColumns extends GenericLayout {
    public NRowsXNColumns(List<T extends Div> containers) {
        // Do something with each container that extends Div class
        for(T extends Div container: containers) {
            container.display();
        }
    }
}

Unfortunately it doesn't compile.


Solution

  • You can restrict types in generics, such as declaring a List<? extends Div>, but you cannot use that notation when declaring the loop variable container:

    for (Div container : containers) {
        container.display();
    }
    

    Since all the objects in containers must be Div or a subclass of Div, they can all be assigned to a variable declared simply as a Div.

    (In a generic method, you can define <T extends Div> and then declare the list as List<T extends Div>, but there's no such definition of T present in this case.)