I am learning Java Generics these days. Right now,I am going through "Type Eraser" concept. I have put together a small java program based on this. Here is my complete code:
/*
* Bridge method demonstration
*/
class Node<T>{
public T data;
public Node(T data){
this.data = data;
}
public void setData(T data){
System.out.println("Node.setData");
this.data = data;
}
}
class MyNode extends Node<Integer>{
public MyNode(Integer data){ super(data); }
public void setData(Integer data){
System.out.println("MyNode.setData");
super.setData(data);
}
}
Now,the following code throws ClassCastException:
// Bridge method demo
System.out.println("Demonstrating bridge method:");
MyNode mn = new MyNode(5);
Node n = mn;
n.setData("Hello");
Integer x = mn.data;
Error:
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at MyNode.setData(genericfirst.java:96)
at genericfirst.main(genericfirst.java:177)
Can somebody help me understand what exactly is causing the problem. Since I am unable to guess what's happening,I think I have not understood the concept of bridge method properly. It would be helpful if someone can explain a little bit about bridge methods too.