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
3 answers
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