I am really having a tough time understanding the wild card parameter. I have a few questions regarding that.
?as a type parameter can only be used in methods. eg:printAll(MyList<? extends Serializable>)I cannot define classes with?as type parameter.I understand the upper bound on
?.printAll(MyList<? extends Serializable>)means: "printAllwill printMyListif it has objects that implement theSerialzableinterface."
I have a bit of an issue with thesuper.printAll(MyList<? super MyClass>)means: "printAllwill printMyListif it has objects ofMyClassor any class which extendsMyClass(the descendants ofMyClass)."
Correct me where I went wrong.
In short, only T or E or K or V or N can be used as type parameters for defining generic classes. ? can only be used in methods
Update 1:
public void printAll(MyList<? super MyClass>){
// code code code
}
Accordint to Ivor Horton's book, MyList<? super MyClass> means that I can print MyList if it has objects of MyClass or any of the interfaces or classes it implements. That is, MyClass is a lower bound. It is the last class in the inheritance hierarchy. This means my initial assumption was wrong.
So, say if MyClass looks like:
public class MyClass extends Thread implements ActionListener{
// whatever
}
then, printAll() will print if
1. There are objects of MyClass in the list
2. There are objects of Thread or ActionListener in the List
Update 2:
So, after having read the many answers to the question, here is my understanding:
? extends Tmeans any class which extendsT. Thus, we are referring to the children ofT. Hence,Tis the upper bound. The upper-most class in the inheritance hierarchy? super Tmeans any class / interface which issuperofT. Thus we are referring to all the parents ofT.Tis thus the lower bound. The lower-most class in the inheritance hierarchy