package practice;
class Node<T> {
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); }
@Override
public void setData(Integer data) {
System.out.println("MyNode.setData");
super.setData(data);
}
}
public class Practice {
public static void main(String[] s)
{
MyNode mn = new MyNode(5);
Node n = mn; // A raw type - compiler throws an unchecked warning
n.setData("Hello"); // Causes a ClassCastException to be thrown.
Integer x = mn.data;
}
}
爲什麼在n.setData("Hello");
這個代碼拋出異常時,實際上它應該扔在Integer x = mn.data;
例外呢?泛型類型擦除ClassCastException異常
http://docs.oracle.com/javase/tutorial/java/generics/bridgeMethods.html
請檢查編輯 – user1232138