I am going through this link (Chapter 4. Types, Values, and Variables) and did not understand below point:
The relationship of wildcards to established type theory is an interesting one, which we briefly allude to here. Wildcards are a restricted form of existential types.
Given a generic type declaration G<T extends B>, G<?> is roughly analogous to Some X <: B. G<X>
.
I appreciate if you provide good example to understand above point clearly.
Thanks in advance.
The wording and formatting of this statement are a bit unlucky*. The link in the answer by Maouven actually covers the general topic pretty well, but one can try to focus on the particular case of Java and Wildcards here:
This basically says that the type parameter of the
G
is any subtype ofB
. And this is always the case, even when you don't say it explicitly.Consider the following snippet, which hopefully illustrates the point:
The object that you obtain by calling
g.get()
is of typeB
, because the declaration ofG<T extends B>
guarantees that any type parameter (even if it is the?
wildcard) always be "at least" of typeB
.(In contrast to that: If the declaration only was
G<T>
, then the type obtained fromg.get()
would only be of typeObject
)The relationship is described as "roughly analogous" to the type theoretic notation. You can probably imagine this as saying: If the declaration is
G<T extends B>
, and you use the typeG<?>
, then this roughly (!) means: There exists a typeX extends B
, and the?
here stands for this (unknown) typeX
.An aside: Note that this also refers to Insersection Types. If you declared the class as
class G<T extends B & Runnable>
, then the statementswould both be valid.
* The "unlucky" formatting referred to the fact that the source code of this paragraph actually reads
making clearer that the word "Some" already is part of the type that is being defined there formally...