tags:

views:

126

answers:

3

Simple example:

public class Person
{
    String name;
}

public class VIP extends Person
{
    String title;
}

And then doing:

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 on "printNames(vipList)" (required List<Person> found List<VIP>).

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

+10  A: 

That's right. A list of bananas is not a list of fruit. Otherwise you could insert any fruit in a list of bananas. e.g.

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

would result in unexpected or counterintuitive results.

Brian Agnew
Try with List<? extends Fruits> lf = new List<Banana>(); That way Java will know that it can be a list of "some child" and will not allow using lf.add(new Apple()) but will allow the asigment of the list.
helios
+8  A: 

You're just prohibited by the rules of Generics. If you're rather interested in how to "fix" this behaviour, just change the printNames() method to take a List<? extends Person> argument instead.

BalusC
That's a good tutorial you're linking to.
Knut Arne Vedaa
You can almost be certain that the best tutorials are been provided by the vendor itself :) You can find them by just Googling "[keyword] tutorial site:sun.com". For example: http://google.com/search?q=generics+tutorial+site:sun.com It's already the 1st hit.
BalusC
+1  A: 

Bjarne Stroustrup, inventor of C++, explains it rather well:

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

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

amn