Why can’t i have classcastexception?
E means C in the example, doesn’t it?
B is not C, I thought my cast must work only for compiler.
Where is my mistake?
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?
}
}
This is because of type erasure in generics. Since you have generic type
<E extends B>statementreturn (E) new B()is compiled intoreturn (B) new B()so you have not gotClassCastException.