1

I don't understand the differences between these two patterns. Can wildcard extends only my classes and generic methods not? But I don't think this is the answer.

cocoricò
  • 51
  • 4
  • 3
    Does this answer your question? [When to use generic methods and when to use wild-card?](https://stackoverflow.com/questions/18176594/when-to-use-generic-methods-and-when-to-use-wild-card) – Scratte Jul 13 '20 at 17:21

1 Answers1

1

A wildcard in Java represents an unknown type and they can be used as return type. To quote the explanation given in the Oracle Java tutorial:

The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable; sometimes as a return type (though it is better programming practice to be more specific). The wildcard is never used as a type argument for a generic method invocation, a generic class instance creation, or a supertype. See this

Let's say you have a List<String> and you would try to pass it to method that accepts List<Object>, it will not compile (Java is trying to protect you from creating a runtime exception here). However, if you pass it to a method that accepts List<?> it will. This may give you a feeling about how wildcards can be useful.

The keyword extends is used for wildcards with an upper bound, e.g. List<? extends Object>. There is also the wildcard with a lower bound: List<? super String>.

Without wildcards, the whole topic of generics would be much less interesting because generics are treated as objects (type erasure). This means that there are not many methods available for them. Wildcards solve this by restricting the type (and thus a common interface, which includes a common set of methods that can be invoked on an object, is specified).

Sergio
  • 36
  • 4