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: "printAll
will printMyList
if it has objects that implement theSerialzable
interface."
I have a bit of an issue with thesuper
.printAll(MyList<? super MyClass>)
means: "printAll
will printMyList
if it has objects ofMyClass
or 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 T
means any class which extendsT
. Thus, we are referring to the children ofT
. Hence,T
is the upper bound. The upper-most class in the inheritance hierarchy? super T
means any class / interface which issuper
ofT
. Thus we are referring to all the parents ofT
.T
is thus the lower bound. The lower-most class in the inheritance hierarchy