Lower Bounded Wildcard References: <? super Type>
Using a reference of type Node<? super Number>, where Type is Number, we can only put a Number or a subtype object of Number into the node, as such a number would also be a subtype object of any supertype of Number. Since we cannot guarantee which specific supertype of Number the node actually has, we cannot put any supertype object of Number in the node. The code below shows what would happen if an unrelated supertype object was put in as data in a Node<? super Number>. If (1) were allowed, we would get a ClassCastException at (2) because the data value (of a supertype) cannot be assigned to a Number reference (which is a subtype).
Node<Number> numNode = new Node<>(2020, null);
Node<? super Number> s0 = numNode;
s0.setData(object); // (1) If this set operation was allowed,
number = numNode.getData(); // (2) we would get an exception here.
Since the type of the reference s0 is Node<? super Number>, the reference s0 can refer to a node containing an object whose type is either Number or some supertype of Number. When we get the data from such a node, we can only safely assume that it is an Object. Keeping in mind that a reference of a supertype of Number can refer to objects that are unrelated to Number (e.g., an Object reference that can refer to a String), if (3) were allowed in the code below, we would get a ClassCastException at (3):
Node<Object> objNode = new Node<>(“Hi”, null); // String as data.
Node<? super Number> s0 = objNode;
number = s0.getData(); // (3) If allowed, we would get an exception here.
object = s0.getData(); // This is always ok.
Leave a Reply