Hubbry Logo
search
logo

Wildcard (Java)

logo
Community Hub0 Subscribers
Write something...
Be the first to start a discussion here.
Be the first to start a discussion here.
See all
Wildcard (Java)

In the Java programming language, the wildcard ? is a special kind of type argument that controls the type safety of the use of generic (parameterized) types. It can be used in variable declarations and instantiations as well as in method definitions, but not in the definition of a generic type. This is a form of use-site variance annotation, in contrast with the definition-site variance annotations found in C# and Scala.

Unlike arrays (which are covariant in Java), different instantiations of a generic type are not compatible with each other, not even explicitly. For example, the declarations

will cause the compiler to report conversion errors for both castings (Generic<Subtype>)superGeneric and (Generic<Supertype>)subGeneric.

This incompatibility can be softened by the wildcard if ? is used as an actual type parameter. Generic<?> is a supertype of all parameterizarions of the generic type Generic. This allows objects of type Generic<Supertype> and Generic<Subtype> to be safely assigned to a variable or method parameter of type Generic<?>. Using Generic<? extends Supertype> allows the same, restricting compatibility to Supertype and its children. Another possibility is Generic<? super Subtype>, which also accepts both objects and restricts compatibility to Subtype and all its parents.

In the body of a generic unit, the (formal) type parameter is handled like its upper bound (expressed with extends; Object if not constrained). If the return type of a method is the type parameter, the result (e.g. of type ?) can be referenced by a variable of the type of the upper bound (or Object). In the other direction, the wildcard fits no other type, not even Object: If ? has been applied as the formal type parameter of a method, no actual parameters can be passed to it. However, objects of the unknown type can be read from the generic object and assigned to a variable of a supertype of the upperbound.

Sample code for the Generic<T extends UpperBound> class:

Sample code that uses the Generic<T extends UpperBound> class:

A bounded wildcard is one with either an upper or a lower inheritance constraint. The bound of a wildcard can be either a class type, interface type, array type, or type variable. Upper bounds are expressed using the extends keyword and lower bounds using the super keyword. Wildcards can have at most one bound - either an upper bound or a lower bound, but not both.

See all
User Avatar
No comments yet.