【发布时间】:2010-06-07 17:43:47
【问题描述】:
很明显,父类的对象可以持有对子类的引用,但在参数化集合的情况下这不成立吗??
例如:
Car class is parent of Sedan
所以
public void doSomething(Car c){
...
}
public void caller(){
Sedan s = new Sedan();
doSomething(s);
}
显然是有效的
但是
public void doSomething(Collection<Car> c){
...
}
public void caller(){
Collection<Sedan> s = new ArrayList<Sedan>();
doSomething(s);
}
编译失败
有人可以指出原因吗?以及如何实现这样一个场景,其中一个函数需要遍历父对象的集合,只修改父类中存在的字段,使用父类方法,但调用方法(比如 3 个不同的方法)传递三种不同的亚型..
当然,如果我这样做,它编译得很好:
public void doSomething(Collection<Car> c){
...
}
public void caller(){
Collection s = new ArrayList<Sedan>();
doSomething(s);
}
【问题讨论】:
标签: java generics inheritance