Example,
Order of inheritance is assumed as O > S > T > U > V
Using extends Keyword ,
Correct:
List<? extends T> Object = new List<T>();
List<? extends T> Object = new List<U>();
List<? extends T> Object = new List<V>();
InCorrect:
List<? extends T> Object = new List<S>();
List<? extends T> Object = new List<O>();
super Keyword:
Correct:
List<? super T> Object = new List<T>();
List<? super T> Object = new List<S>();
List<? super T> Object = new List<O>();
InCorrect:
List<? super T> Object = new List<U>();
List<? super T> Object = new List<V>();
Adding object:
List Object = new List();
Object.add(new T()); //error
But Why error ?
Let's look at the Possibilities of initializations of List Object
List<? extends T> Object = new List<T>();
List<? extends T> Object = new List<U>();
List<? extends T> Object = new List<V>();
If we use Object.add(new T()); then it will be correct only if
List<? extends T> Object = new List<T>();
But there are extra two possibilities
List Object = new List();
List Object = new List();
If we try to add (new T()) to the above two possibilities it will give an error because T is the superior class of U and V . we try to add a T object [which is (new T()) ] to List of type U and V . Higher class object(Base class) cannot be passed to lower class Object(Sub class).
Due to the extra two possibilities , Java gives you error even if you use the correct possilibity as Java don't know what Object you are referring to .So you can't add objects to List Object = new List(); as there are possibilities that are not valid.
Adding object:
List Object = new List();
Object.add(new T()); // compiles fine without error
Object.add(new U()); // compiles fine without error
Object.add(new V()); // compiles fine without error
Object.add(new S()); // error
Object.add(new O()); // error
But why error occurs in the above two ?
we can use Object.add(new T()); only on the below possibilities,
List<? super T> Object = new List<T>();
List<? super T> Object = new List<S>();
List<? super T> Object = new List<O>();
If we Tried to use Object.add(new T()) in
List Object = new List();
and
List Object = new List();
then it will give error
This is because
We can't add T object[which is new T()] to the List Object = new List(); because it is an object of type U . We can't add a T object[which is new T()] to U Object because T is a base class and U is a sub class . We can't add base class to subclass and that's why error occurs . This is same for the another case .