Java Inheritance doubt in parameterised collection

Posted by Gala101 on Stack Overflow See other posts from Stack Overflow or by Gala101
Published on 2010-06-07T17:43:47Z Indexed on 2010/06/07 17:52 UTC
Read the original article Hit count: 200

Filed under:
|

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);
}

© Stack Overflow or respective owner

Related posts about java

Related posts about inheritance