I had 2 classes as below. From my understanding compiler must not complain at line 4 (class WildCard) as my parametrized type is (Node? super Number> s0), as object is super to number in parametrized type. but compiler is complaining at 4,8 and 9. why so.
public class Node<E> {
private E data;
public void setData(E obj) {
data = obj;
}
public E getData() {
return data;
}
}
public class WildCard {
static void checkIt(Node<? super Number> s0)
{
Object object=new Object(); //1
Number number =1.5; //2
Integer integer=10; //3
s0.setData(object); //4
s0.setData(number); //5
s0.setData(integer); //6
object=s0.getData(); //7
number=s0.getData(); //8
integer=s0.getData(); //9
}
}
The problem is as follows:
Node<? super Number>means you could pass in anyNodewith a parameter that is of typeNumberor a super type, e.g.Object.Since you don’t know the exact type of that generic parameter some operations are not allowed.
Here’s a short breakdown of why some lines compile and some don’t:
s0.setData(object);doesn’t compile because you could have aNode<Number>which would not all you to add an arbitrary objects0.setData(number);compiles sinceNumbermatches all possible types for the parameters0.setData(integer);compiles becauseIntegerextendsNumberand thus the line above appliesobject=s0.getData();compiles because any data object extendsObject, alwaysnumber=s0.getData();doesn’t compile because you could have aNode<Object>and thus the data object might have a different type (e.g.String)integer=s0.getData();doesn’t compile, same reason as the line above