Why can't, for example, a List <ChildClass> be passed to a method that takes a List <ParentClass> parameter as a parameter?

A simple example:

public class Person { String name; } public class VIP extends Person { String title; } 

And then do:

 public static void main(String[] args) { Person p = new Person(); p.name = "John"; VIP vip = new VIP(); vip.name = "Bob"; vip.title = "CEO"; List<Person> personList = new ArrayList<Person>(); List<VIP> vipList = new ArrayList<VIP>(); personList.add(p); personList.add(vip); vipList.add(vip); printNames(personList); printNames(vipList); } public static void printNames(List<Person> persons) { for (Person p : persons) System.out.println(p.name); } 

gives an error message "printNames (vipList)" (requires List <Person> found list <VIP>).

Does this mean that although the VIP is Person, the List <VIP> is not a List <Person>?

+4
source share
3 answers

You are simply forbidden by the rules of Generics . If you're interested in how to “fix” this behavior, just change the printNames() method to accept the List<? extends Person> argument instead List<? extends Person> List<? extends Person> .

+9
source

It is right. The banana list is not a list of fruits. Otherwise, you can insert any fruit into the banana list. eg.

 List<Fruit> lf = new List<Banana>(); lf.add(new Apple()); 

will lead to unexpected or conflicting results.

+11
source

Bjarne Straustrup, inventor of C ++, explains this pretty well:

http://www2.research.att.com/~bs/bs_faq2.html#conversion

Yes, I know I'm late for this party, but better than never, right ..

+1
source

Source: https://habr.com/ru/post/1299330/


All Articles