Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't e.g. List<ChildClass> be passed to a method that takes a List<ParentClass> as parameter?

Tags:

java

generics

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>?

like image 439
Knut Arne Vedaa Avatar asked Nov 30 '22 19:11

Knut Arne Vedaa


2 Answers

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.

like image 129
Brian Agnew Avatar answered May 21 '23 21:05

Brian Agnew


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.

like image 35
BalusC Avatar answered May 21 '23 22:05

BalusC