9

If I have a method in MyClass such as

setSuperClassList(List<Superclass>)

...should I be able to do this:

new MyClass().setSuperClassList(new ArrayList<Subclass>())

It appears this won't compile. Why?

jjnguy
  • 136,852
  • 53
  • 295
  • 323
Drew Johnson
  • 18,973
  • 9
  • 32
  • 35

4 Answers4

23

Try setSuperClassList(List<? extends Superclass>).

Also check PECS to see wether you should use ? extends or ? super.

Thomas Lötzer
  • 24,832
  • 16
  • 69
  • 55
6

You are just doing the generics a bit wrong. Add the ? extends bit, and that will allow the passed in list to contain the SuperClass or any of its subclasses.

setSuperClassList(List<? extends Superclass>)

This is called setting an upper bound on the generics.

The statement List<Superclass> says that the List can only contain SuperClass. This excludes any subclasses.

jjnguy
  • 136,852
  • 53
  • 295
  • 323
1

It won't compile sincejava.util.List is not covariant.

Try setSuperClassList(List<? extends Superclass>) instead.

missingfaktor
  • 90,905
  • 62
  • 285
  • 365
0

Do:

setSuperClassList(List<? extends Superclass> list)

This will allow a list of any subclass of Superclass.

Manuel Darveau
  • 4,585
  • 5
  • 26
  • 36