Wildcard (Java)
The wildcard (rarely also Joker )? in Java is a special type of current parameters for instantiating generic ( parameterized ) types. In this article, the most important rules for its use are summarized.
Covariance for generic types
In contrast to arrays (which are covariant in Java) are different instantiations of a generic type with each other (not even explicitly ) compatible: Under the agreements Generic
This incompatibility can be softened with the wild card, though? is used for an actual type parameters: Generic is the abstract supertype of all instantiations of the generic type >. That is to say, of this type, only references, not objects can be formed. The purpose of such a reference is that style to match any instantiations of a generic nature.
Wildcard as a parameter type
In the body of the generic unit of the type parameter ( if full, then as Object) handled as the upper bound. If the result type (return type) is a function of the type parameter, the result ( eg type? ) In a reference to the type of barrier (Object, if no barrier) are adopted. In the other direction, the wildcard type does no other type, not even Object: When? a method was used for the type of the formal parameter, you can pass no parameters. You can then only after conversion ( casting ) are called the wildcard reference:
Class Generic
Not only the formal type parameters, the wildcard can be (further) limited from above, if you do not want to keep any instantiations compatible:
Generic extends UntertypVonSchranke > vonObenEingeschränkteReferenz; In this reference can now be hooked by Generic an instance where the actual type parameter is a subtype of UntertypVonSchranke. In a constraint from below
Generic super UntertypVonSchranke > vonUntenEingeschränkteReferenz; able instantiations of generic with any supertype are mounted ( eg barrier) of UntertypVonSchranke. It is therefore possible that the approved types are restricted from two sides: from the top through the class agreement ( extends barrier), from below by reference agreement ( super UntertypVonSchranke ).
Object creation with wildcard instantiations
Although wildcard instantiations no objects can be created (new Generic > ( ) Is therefore prohibited because Generic > Abstract is ), Array objects can only unrestricted wildcard instantiations ( ie no other generic instantiations ) generated
be: > new Generic is correct, while new Generic