0
    List<? extends Person> list1 = null;
    List<? super Person> list2 = null;

    List<Student> list3 = new ArrayList<>();
    List<Person> list4 = new ArrayList<>();
    List<Object> list5 = new ArrayList<>();

    list3.add(new Student());

    list1 = list3;
    Person p1 = list1.get(0);
  //Student s1 = list1.get(0);

Student is a subclass of Person;(Student extends Person)

My question is why list1.get(0) cannot be directly referenced(Like the last commented statement) by an object of the Student class because the elements of list3 can only be objects of Student class or objects of its subclasses. Using variables like 'Student s1' on the left would be okay to reference an object of its subclass on the right.

Teymour
  • 1,832
  • 1
  • 13
  • 34
Liu
  • 67
  • 1
  • 6
  • 2
    All `list1` knows is that it's a list of some class that extends `Person`. It doesn't know that it's a list of `Student` - that's not how it's defined. – RealSkeptic Jan 08 '20 at 17:52
  • Try to look here [Look at Generics - Get and Put rule.](https://stackoverflow.com/questions/1292109/explanation-of-the-get-put-principle) there is a very useful explanation. – Giovanni Leo Jan 08 '20 at 17:56
  • So the left-hand side reference cannot be too specific as there is a question mark which means "can be many subclasses but not one specific subclass". Is that what you mean? – Liu Jan 08 '20 at 17:57

0 Answers0