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>).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With