Wildcard (Java): Difference between revisions

Content deleted Content added
RippleSax (talk | contribs)
RippleSax (talk | contribs)
Line 5:
Unlike arrays (which are [[Covariance and contravariance (computer science)#Covariant arrays in Java and C#|covariant]] in Java), different instantiations of a generic type are not compatible with each other, not even explicitly: With the declaration <code>Generic<Supertype> superGeneric; Generic<Subtype> subGeneric;</code> the compiler would report a conversion error for both castings <code>(Generic<Subtype>)superGeneric</code> and <code>(Generic<Supertype>)subGeneric</code>.
 
This incompatibility may be softened by the wildcard if <code>?</code> is used as an actual type parameter: <code>Generic<?></code> is the abstract supertype for all parameterizarions of the generic type. This this allows objects of type <code>Generic<Supertype></code> and <code>Generic<Subtype></code> to be safely assigned to a variable or method parameter of type <code>Generic<?></code>. Using <code>Generic<? extends Supertype></code> allows the same, restricting compatibility to <code>Supertype</code> and its children. Another possibility is <code>Generic<? super Subtype></code>, which also accepts both objects and restricts compatibility to <code>Subtype</code> and all its parents.
 
== Wildcard as parameter type ==