0

为什么我不能有 classcastexception?E 在示例中表示 C,不是吗?B 不是 C,我认为我的演员表必须只适用于编译器。我的错误在哪里?

public class A{
public static void main(String...s){
    Monitor<C> m = new Monitor<C>(); 
    C arg2 = new C();
    B d = m.f(arg2);
    System.out.println(d);
    }
}
class B extends A{}
class C extends B{}
class Monitor<E extends B>{
public E f(E E){
    return (E) new B();//Why this place didn't give me ClassCastException?
}
}
4

2 回答 2

3

Read the tutorial about generics: http://docs.oracle.com/javase/tutorial/java/generics/

Because of type erasure you cannot cast to E, see http://docs.oracle.com/javase/tutorial/java/generics/restrictions.html

于 2012-11-24T12:47:26.350 回答
0

This is because of type erasure in generics. Since you have generic type <E extends B> statement return (E) new B() is compiled into return (B) new B() so you have not got ClassCastException.

于 2012-11-24T12:51:42.037 回答