Take the 2-minute tour ×
package pkg_2;

import java.util.*;

class shape{}

class Rect extends shape{}

class circle extends shape{}

class ShadeRect extends Rect{}

public class OnTheRun {

        ShadeRect sr = new ShadeRect();
        List<? extends shape> list = new LinkedList<ShadeRect>();       

share|improve this question
So, what are you asking here? –  zigdon Oct 13 '10 at 5:48
Lowercase class names are not exactly right. –  Thilo Oct 13 '10 at 5:50
compiler is complaining about the last line & tell me error i cannot understanding it –  MineIsMine Oct 13 '10 at 5:51

1 Answer 1

up vote 6 down vote accepted

You cannot add anything to a List<? extends X>.

The add cannot be allowed because you do not know the component type. Consider the following case:

List<? extends Number> a = new LinkedList<Integer>();
a.add(1);  // in this case it would be okay
a = new LinkedList<Double>();
a.add(1);  // in this case it would not be okay

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):

Number[] a = new Integer[1];
a[0] = 1;  // okay
a = new Double[1];
a[0] = 1;  // runtime error

As for your program, you probably just want to say List<shape>. You can put all subclasses of shape into that list.

ShadeRect sr = new ShadeRect();
List<shape> list = new LinkedList<shape>();       
share|improve this answer
Thank you , excellent answer..... –  MineIsMine Oct 13 '10 at 6:08
+1 - Nice explanation. –  Johnbabu Koppolu Oct 13 '10 at 6:19

Your Answer


