Adding to list with upper bounded wildcards in java

205 views Asked by At

Given the following code:

public class Test{

    static class Bird{}
    static class Sparrow extends Bird{}
    
    public static void main(String args[]){
    
    List<? extends Bird> list = new ArrayList<Bird>();
   
    list.add(new Bird()); //Does not compile ...line 1
    list.add(new Sparrow());//Does not compile ...line 2
     
    }
}

Can someone explain why I cannot add the object of new Bird() and the object of new Sparrow() into the list? I was expecting line 1 and line 2 to compile since the class Sparrow is a subclass of Bird, and Bird is itself.

0

There are 0 answers