I am stuck with a code that I do not understand why it works. Assume that I create a generic interface Foo<T>
as following:
interface Foo<T>{
void set(T item);
}
Then I create a class called Bar
which implements Foo<String>
as following:
class Bar implements Foo<String>{
@override
public void set(String item){
//useless body
}
}
Based on this we can writes following code:
Bar bar = new Bar();
bar.set("Some string");
Foo rawFoo = (Foo) bar;
rawFoo.set(new Object()); // ClassCastException: Object cannot be cast to string
That last line is the one that I don't really get. As it's known that when using raw types the generic parameter types are converted to Object
.
In this case the code compiles and we can pass Object to set()
method. But how Java determines that it has to cast the Object to String at runtime?