In the below example "Apple" is the super type of anything that can be added to the array. In the example below "Apple" or any of its subtypes are allowed to be added to the list. However only "Object" instances are allowed to be retrieved. Since only Apple and it's subtypes are allowed , why doesn't Java allow the values to be mapped to "Apple" instances?
class Fruit {
@Override
public String toString() {
return "I am a Fruit !!";
}
}
class Apple extends Fruit {
@Override
public String toString() {
return "I am an Apple !!";
}
}
class AsianApple extends Apple {
@Override
public String toString() {
return "I am an AsianApple !!";
}
}
public class GenericsExamples
{
public static void main(String[] args)
{
//List of apples
List<Apple> apples = new ArrayList<Apple>();
apples.add(new Apple());
//We can assign a list of apples to a basket of apples
List<? super Apple> basket = apples;
basket.add(new Apple()); //Successful
basket.add(new AsianApple()); //Successful
basket.add(new Fruit()); //Compile time error
basket.add(new Object()); //Compile time error
Object fruit1 = basket.get(0); //works
Apple appleFruit = basket.get(0); // compiler error
}
}