Implementing generics in Java

64 views Asked by At
    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.

0

There are 0 answers