[英]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 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>). 在“printNames(vipList)”上给出错误(必需的List <Person> found List <VIP>)。
Does this mean that although VIP is a Person, List<VIP> is not a List<Person>? 这是否意味着虽然VIP是Person,但List <VIP>不是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.
否则你可以在香蕉列表中插入任何水果。 eg
例如
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>
如果您对如何“修复”此行为感兴趣,只需更改
printNames()
方法以获取List<? extends Person>
List<? extends Person>
argument instead. 改为
List<? extends Person>
参数。
Bjarne Stroustrup, inventor of C++, explains it rather well: C ++的发明者Bjarne Stroustrup解释得很好:
http://www2.research.att.com/~bs/bs_faq2.html#conversion http://www2.research.att.com/~bs/bs_faq2.html#conversion
Yes, I know I am late for this party, but better than never, right.. 是的,我知道我参加这个派对已经迟到了,但总比没有好,对吧..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.