1
public class Father {
    public String name;
    public Father(String name){
        this.name=name;
    }
}

public class Son extends Father {

    public Son(String name) {
        super(name);
    }
}

public class Ten {
    public static void main(String[] args) {
        Father father=new Son("Ramesh");
        System.out.println(father.name);
        List<? extends Father> list=new ArrayList<Son>();
        list.add(father);
        for (Father father1:list) {
            System.out.println(father1.name);
        }
    }
}

I am getting this compilation error Error:(11, 16) java: no suitable method found for add(com.adp.quest.Father) method java.util.Collection.add(capture#1 of ? extends com.adp.quest.Father) is not applicable (argument mismatch; com.adp.quest.Father cannot be converted to capture#1 of ? extends com.adp.quest.Father) method java.util.List.add(capture#1 of ? extends com.adp.quest.Father) is not applicable (argument mismatch; com.adp.quest.Father cannot be converted to capture#1 of ? extends com.adp.quest.Father)

Kindly explain why I am getting this on list.add(father)?

Andey
  • 21
  • 3
  • Lets say you have `AnotherFather` that extends `Father` but is not subclass of `Son` how can compiler make sure you wont add it to `list` which only accepts `Son` or its subtypes. – tsolakp Jan 29 '18 at 19:32
  • The compiler sees you trying to add a variable of type `Father` to something that could be a `List`; and since the object referred to by a variable of type `Father` isn't necessarily a `Son`, the compiler can't guarantee that this operation will work. So the compiler shows you an error, in order to enforce type safety. – Dawood ibn Kareem Jan 29 '18 at 19:33
  • [How can I try to explain...?](https://youtu.be/yERildSsWxM) – Andy Turner Jan 29 '18 at 19:36

0 Answers0