Tuesday, April 26, 2011

Java Generics: Covariance and Contravariance

I was reading this nice introduction to Generics, and I realized that the terms "covariance" and "contravariance" were obscure to me, although I was familiar with the "?" notations:


* List<? extends Fruit>  (means: the list can contain Fruit and any subclasses of Fruit)

* List<? super Apple>  (means: the list can contain Apple and any superclass of Apple)

Here a more formal (and boring) discussion on the terminology


covariant: converting from wider (double) to narrower (float).

contravariant: converting from narrower (float) to wider (double).



which leads to the interesting PECS (Producer Extends Consumer Super) pattern very well explained here

No comments: