简体   繁体   中英

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?

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();
}

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