-1

I have a derived class Father and a base class Parent e.g.

public static class Parent {
}
public static class Father extends Parent {
}

I wonder why the followings are not allowed?

public static List<Parent> foo() {
    List<? extends Parent> list = new ArrayList<>();
    list.add(new Parent());  // 1. why is this not allowed?
    list.add(new Father());  // 2. why is this not allowed?
    return list;  // 3. why is this not allowed?
}
user1589188
  • 5,316
  • 17
  • 67
  • 130
  • The duplicate explains why 1 and 2 are not allowed, and should implicitly explain why 3 is also not allowed. You may also want to check out: [Is List a subclass of List? Why are Java generics not implicitly polymorphic?](https://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-are-java-generics-not-implicitly-po/2745306). – Slaw Jan 18 '21 at 05:46

2 Answers2

1

you can try this below code->

 public static List<Parent> foo() {
        List<Parent> list = new ArrayList<>();
        list.add(new Parent());  // 1. why is this not allowed?
        list.add(new Father());  // 2. why is this not allowed?
        return list;  // 3. why is this not allowed?
    }
0

Having ? extends Parent as a generic parameter means that it represents a class that extends Parent, and therefore not Parent itself. To include Parent itself, simply use Parent as the generic parameter (i.e. List<Parent>).

Pieter12345
  • 1,713
  • 1
  • 11
  • 18