Java Inheritance doubt in parameterised collection
- by Gala101
It's obvious that a parent class's object can hold a reference to a child, but does this not hold true in case of parameterised collection ??
eg:
Car class is parent of Sedan
So
public void doSomething(Car c){
...
}
public void caller(){
Sedan s = new Sedan();
doSomething(s);
}
is obviously valid
But
public void doSomething(Collection<Car> c){
...
}
public void caller(){
Collection<Sedan> s = new ArrayList<Sedan>();
doSomething(s);
}
Fails to compile
Can someone please point out why? and also, how to implement such a scenario where a function needs to iterate through a Collection of parent objects, modifying only the fields present in parent class, using parent class methods, but the calling methods (say 3 different methods) pass the collection of three different subtypes..
Ofcourse it compiles fine if I do as below:
public void doSomething(Collection<Car> c){
...
}
public void caller(){
Collection s = new ArrayList<Sedan>();
doSomething(s);
}