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 Upper generic; Generic under generic; the compiler reports in both conversions ( castings ) ( Generic ) above generic and ( Generic ) under a generic error.

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 {      private T t;      void write (T t ) { this.t = t; }      T read () {return t; } } ... Generic joker reference; O barrier = jokerReferenz.lesen (); / / Object would also be OK jokerReferenz.schreiben ( new Object ()); / / Type error. ( ( Generic ) joker reference) write (new barrier ()); / / OK Restriction of wildcard

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 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 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 is prohibited.

448970
de