Eleanore February 2016

Generics + Interfaces in Java

Consider this example:

class Parent<T> implements MyInterface<T> {...}
class Child1 extends Parent<ConcreteType1>{...}
class Child2 extends Parent<ConcreteType2>{...}

and then the following factory:

public class Factory<T> {
    public static <T> Parent<T> getChild(Type type) {
        switch (type) {
            case value1:
                return new Child1();
            case value2:
                return new Child2();
        }
    }
}

The Type parameter is just an enum.

Now,

  • if I leave the things as above, I get the following error: cannot convert Child1 to Parent<T>
  • if I remove the generics, leaving just Parent and not Parent<T>, I get a warning

How can I fix this issue?

Answers


Robert Bräutigam February 2016

The method does not really know the exact type of T, so you could just return a Parent<?>:

public static Parent<?> getChild(Type type) {
    ...
}

Or, you could extend the Type class to actually construct the children, and with that you would have control over the exact output:

public static <T> Parent<T> getChild(Type<T> type) {
    return type.createChild();
}

Post Status

Asked in February 2016
Viewed 1,290 times
Voted 6
Answered 1 times

Search




Leave an answer