I am just wondering, why the assignment of a wrong type value does not lead to any runtime exception. I prepared a little example, where class X holds a generic variable "object" that implements Interface A and class Y declares this generic to be of type B
public interface A{};
public class B implements A{}
public class C implements A{}
public class X<T extends A>{
T object;
void setObject(T t){
object = t;
}
T getObject(){
return object;
}
}
public class Y extends X<B>{}
If I have a variable of type X holding and Y-Object, the compiler allows the assignment of any value, which is correct from my opinion. But at runtime, I would expect an exception.
public static void main(String[] args) throws Exception{
X<A> foo = (X<A>) Class.forName("com.abc.Y").newInstance();
foo.setObject(new B()); //should not fail
foo.setObject(new C()); //should fail
}
I don't get any exceptions, until class Y, tries to access the object.
If I add this method to class Y, I get a ClassCastException on setObject, but I actually don't want to override all Methods with the correct Class.
public class Y extends X<B>{
void setObject(B t){
super.setObject(t);
}
}