public class Node<T> {
private T objReference;
private Node<T> nextReference;
public Node(Object ref) {
objReference = (T) ref;
nextReference = null;
}
public Node() {
objReference = null ;
nextReference = null ;
}
public void assignNextReference(Node ref) {
this.nextReference = ref;
}
public Node getNextReference() {
return this.nextReference;
}
public T getObjReference() {
return objReference ;
}
public void assignObjReference(Object ref) {
try {
objReference = (T) ref;
} catch(ClassCastException e) {
System.out.println(e);
}
}
}
I expected the following call to throw a ClassCastException but no exception is thrown.
Node<Integer> n = new Node<Integer>() ;
n.assignObjReference(new String("String"));
When we use Integer for type parameter, assignObjectReference method would try to cast the String reference to the type parameter which is Integer. Since this is not possible, we should be getting a ClassCastException. What am I missing here?