Posts

Showing posts from November, 2014

Java Generics Covariant and Contravariant

Image
Introduction Here the getter method ( ) => A Covariant A <: B ( ) => A <: ( ) => B If a A is subtype of B, then getter or A is subtype of getter of B. Here the setter method A => ( ) Contravariant B => ( ) <: A => ( ) Above Covariant and Contravariant can be explained from the following code: Say A is Animal public class Animal { @Override public String toString(){ return "I am a Animal"; } } Say B is Bear as follows public class Bear extends Animal { @Override public String toString(){ return "I am a Bear"; } }   As shown in the above code Bear is subtype of Animal. Here the Zookeeper class where getter and setter methods are public class Zookeeper { private Animal animal; public void setFeed(Animal animal){ this.animal =animal; } public Animal getFed(){ return this.animal; } } As shown in the above Zookeeper class, there is no indication of Bear,