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?
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.
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? 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).
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.
Try setSuperClassList(List<? extends Superclass>)
.
Also check PECS to see wether you should use ? extends
or ? super
.
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.
It won't compile sincejava.util.List
is not covariant.
Try setSuperClassList(List<? extends Superclass>)
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