The Java tutorial on type erasure doesn\'t seem to detail the specific rules of cast insertion by the compiler. Can someone please explain the specific rules that cause the
The ClassCastException would be throw when a call is made to
n.setData("Hello");
This is because the compiler builds bridge methods to preserve polymorphism. The bridge method will look like:
public void setData(Object data) {
setData((Integer)data); //the exception is thrown here
}
since an instance of a string cannot be converted to Integer, the ClassCastException would be thrown.
You can read about bridge methods here.
MyNode mn = new MyNode(5);
MyNode which defines the generic type T of interface Node as IntegerNode n = (MyNode)mn;
T and use the interface Node completely without generics which will have the following consequence: imagine generic type T to be treated as java.lang.Objectn.setData("Hello");
String, Integer, array, anything else)Integer x = mn.data;
nm.data should return an Integer type as Integer is defined as generic type argument T in the MyNode classString instead, the nm.data holds a String instanceClassCastException