Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics: set List of superclass using List of subclass

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?

like image 821
Drew Johnson Avatar asked Mar 24 '10 20:03

Drew Johnson


People also ask

Is list superclass of ArrayList?

When we examine the API (Application Programming Interface) of Java's ArrayList, we notice that ArrayList has the superclass AbstractList . AbstractList , in turn, has the class Object as its superclass. Each class can directly extend only one class.

Is list integer a subtype of List Number?

Although Integer is a subtype of Number, List<Integer> is not a subtype of List<Number> and, in fact, these two types are not related.

What is subtyping in Java?

What is subtyping? Subtyping is a key feature of object-oriented programming languages such as Java. In Java, Sis a subtype of T if S extends or implements T. Subtyping is transitive, meaning that if R is a subtype of S, then R is also a subtype of T (T is the super type of both Sand R).

Can superclass inherit from subclass?

A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.


3 Answers

Try setSuperClassList(List<? extends Superclass>).

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

like image 84
Thomas Lötzer Avatar answered Oct 26 '22 23:10

Thomas Lötzer


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.

like image 32
jjnguy Avatar answered Oct 26 '22 23:10

jjnguy


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

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

like image 41
missingfaktor Avatar answered Oct 27 '22 00:10

missingfaktor