I'm trying to figure out the whole Java generics topic.
More specifically this issue:
public class Node<E>{
private E data;
public Node(E data){
this.data=data;
}
public E get(){
return this.data;
}
public void set(E data){
this.data=data;
}
}
How can I add an "extends" wildcard specifying that the set method can receive E or any inheriting class of E (in which case the Node will hold a upcasted version of the parameter).
Or will it work even if I leave it the way it is?
(I might be a bit confused with the invariant aspect of generic types.)
Thanks!
Your class is already doing what you require. Lets demonstrate by example. Lets say you have created Node (Number
is super class of Integer
, Long
etc);
Node<Number> numberNode = new Node<Number>(1);
You can call set method by passing its subclasses also
numberNode.set(new Integer(1));
numberNode.set(new Long(1));
You declared your class Node<E>
where it already accepts any inheriting class of E
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With