posted 13 years ago
Suppose you have a class Node :
And suppose you have another class Foo:
1 . What should be put in the n.set() as parameter? It must be null, nothing else.
Reason:
The compiler does not know what the paremter type n can accept. It can be Integer, Double.... What if n takes an Integer type as the E and then you set this.e to a Double? For this reason, the compiler won't let you pass in any object type paremeter to the set method. It applies to all other situation similar to this example.
2. What should be return from n.get() ? It must be Number. Therefore, you can assign Number aNum= n.get(); where aNum is a null.
Reason:
The compiler only knows n takes a Number type. This is the only information it knows.
3. What should be put in the n1.set() as parameter? It must be some types that are Number or its subtype.
Reason:
If n1 accepts E as a Number and you pass in an Integer as the parameter , it will be setting the E e ( E is substituted by Number) to an Integer. That is ok. If you pass in an Object as the parameter, it will be setting the Number e = new Object(); That won't compile at all. For this reason, the compiler won't let you pass in any type that is the super type of Number.
4. What should be return from n1.get()? It must be Object. Therefore you can assign Object o = n1.get();
Reason:
For case 3, you can only set e of the Node class to be a Number, Double, Integer....(subtypes). For sure, the compiler knows you pass in a Number. Why can't we assign Number myNum = n1.get()? Because you may assign the n1 to a node that takes Object like this:
The compiler only knows n1 takes a Number or an object, but it does not know what exactly it is. The safest return type for the get() is only an object.
Thefore, when you are given any class (Node, List....) with generic parameters, a method that takes the generic parameter as argument and a method that returns the object of the generic parameter type, you will think of the above 4 cases.
This is an example from Mughal and Rasmussen's study guide , chapter 13 Generics.
Summary:
What to put for set's parameter:
Node<? extends Number> Node<? super Number>
set Null Number or its subtype
What to return for get method:
Node<? extends Number> Node<? super Number>
get Number or Object Object only