Upper Bounded Wildcard References: – Generics

Upper Bounded Wildcard References: <? extends Type>

The type of the reference s0 is Node<? extends Number>, where Type is Number. This means that the reference s0 refers to a node containing an object whose type is either Number or a subtype of Number, but the specific (sub)type of the object cannot always be determined at compile time. Putting any object, except a null, into such a node might not be type-safe.

The code below shows what would happen if any object was allowed to be set as data in a Long node via its alias s0. If (1), (2), or (3) were allowed, we would get a ClassCastException at (4) because the data could not be assigned to a Long reference, as the type-safety of the node longNode will have been compromised, either with a supertype object or an object of an unrelated type.

Click here to view code image

Long longInt = 20L;
Node<Long> longNode = new Node<>(longInt, null);  // Node of Long, that is
Node<? extends Number> s0 = longNode;// referenced by a Node<? extends Number> ref.
s0.setData(object);                  // If this was allowed, or             (1)
s0.setData(number);                  // if this was allowed, or             (2)
s0.setData(integer);                 // if this was allowed,                (3)
longInt = longNode.getData();        // we would get an exception here.     (4)

The following method call will also not compile, as the compiler cannot give any guarantees at compile time that the reference s0 will refer to a node of Long at runtime:

Click here to view code image

s0.setData(longInt);                 // Compile-time error!

The upper bound in the wildcard type ? extends Number is Number. Therefore, the data of the node with the wildcard type ? extends Number must be a Number (i.e., either an object of type Number or an object of a subtype of Number). Thus we can only safely assign the reference value returned by the get operation to a reference of type Number or a supertype of Number.

Leave a Reply

Your email address will not be published. Required fields are marked *