开发者

Why can't e.g. List<ChildClass> be passed to a method that takes a List<ParentClass> as parameter?

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 ArrayL开发者_运维技巧ist<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>?


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.


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.


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..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜