package pkg_2;
import java.util.*;
class shape{}
class Rect extends shape{}
class circle extends shape{}
class ShadeRect extends Rect{}
public class OnTheRun {
public static void main(String[] args) throws Throwable {
ShadeRect sr = new ShadeRect();
List<? extends shape> list = new LinkedList<ShadeRect>();
list.add(0,sr);
}
}
package pkg_2; import java.util.*; class shape{} class Rect extends shape{} class circle extends shape{}
Share
You cannot add anything to a
List<? extends X>.The
addcannot be allowed because you do not know the component type. Consider the following case:For
List<? extends X>you can only get out objects, but not add them.Conversely, for a
List<? super X>you can only add objects, but not get them out (you can get them, but only as Object, not as X).This restriction fixes the following problems with arrays (where you are allowed these “unsafe” assigns):
As for your program, you probably just want to say
List<shape>. You can put all subclasses of shape into that list.