1

I know what is the difference between the generic type and the wildcard type, but in this situation I cannot use the same way again to understand.

For short, To compare both Interfaces below

public interface RequestParser {
    <T extends Entity> Message<T> parseRequest(String json);
}


public interface RequestParser {
    Message<? extends Entity> parseRequest(String json);
}

Only the first one can compile the below codes: (User extends Entity)

Message<User> message = requestParser.parseRequest(json);

The one uses wildcard ? cannot succeed.

So what exactly is the difference between them in this situation ...?

OOD Waterball
  • 707
  • 1
  • 11
  • 31
  • 2
    Possible duplicate of [What is PECS (Producer Extends Consumer Super)?](https://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super) – Flown Sep 04 '17 at 07:10
  • In this case you want to use the produced value and therefore it's also a consumer (linked in the duplicate) – Flown Sep 04 '17 at 07:12
  • Oops, PECS the term I never heard before, thanks. – OOD Waterball Sep 04 '17 at 07:13

1 Answers1

1

It's because Message<User> is not a subclass of Message<? extends Entity>.

The issue will be more evident when trying to implement RequestParser.

This will fail without a cast, as T is not necessarily AnotherUser:

public class AnotherUser extends Entity {}

public class RequestParserImpl implements RequestParser {
    <T extends Entity> Message<T> parseRequest(String json) {
         return new Message<AnotherUser>();
    }
}

Whereas this will compile:

public class RequestParserImpl implements RequestParser {
    Message<? extends Entity> parseRequest(String json) {
         return new Message<AnotherUser>();
    }
}
Dan Godfrey
  • 456
  • 3
  • 6