简体   繁体   中英

Java wildcard return type for abstract method

The Java documentation for wildcards says that they can be used as return types but it is generally not a good idea. Is this still true if the wildcard is used as the return type for an abstract method but the class that implements this method returns a concrete type? If not, what is the best way to handle this type of situation. Consider the example below. In this case, Entity might be modeled after a JSON REST response, where in the second case the result is just a list of Strings. Is it better to use List<Object> as the return type or something else entirely?

public abstract class AbstractClient {
    public abstract List<?> listEntities();
}

public class ConcreteClient {
    @Override
    public List<Entity> listEntities();
}

public class ConcreteClient2 {
    @Override
    public List<String> listEntities();
}

In such a case it is better to use generics properly instead of using wildcards. Use a type parameter and extend the abstract class with the appropriate argument for the type parameter:

public abstract class AbstractClient<T> {
    public abstract List<T> listEntities();
}

public class ConcreteClient extends AbstractClient<Entity> {
    @Override
    public List<Entity> listEntities();
}

public class ConcreteClient2 extends AbstractClient<String> {
    @Override
    public List<String> listEntities();
}

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