Hi Faber ,
You should remember that there is only one object on heap which is referred by three different type of references , 2 of them are type safe and one is of raw type.
One more thing you should keep in mind when you mix up type safe and raw type it is ok at compile type. But at runtime autual object matters. Hence it can throw Exception.
after line 45 b refers to bO, then after line 46, we cast b to bA. The scary thing happens at line 48 when we set the bA's element with an Apple, thus the bO's element is set too.
line 50 throws runtime exc becos we try to case an Apple to an Orange.
Correct me if i'm wrong.[/QB]
Hi Faber ,
Basket b = bO; //line 45
Now you have lost type safety .
Basket<Apple> bA = (Basket<Apple>
b ;// 46
Now again you cast raw type b to type safe bA.
bA.setElement(new Apple());// 48
Compiler allows it only because it cares about reference type that is bA.
Since bA is raw type that is why compiler lets you do it.
Try to do it with reference with bo
bo.setElement(new Apple());// error
It is compile-time error because knows it very well that bo is of type Basket<Orange> and you are trying to add wrong thing in type safe collection.
Orange o = bO.getElement();
Now since compiler thinks that element should be Orange because of reference type so it allows it.
But at runtime JVM finds that it is Apple object and you are trying to assign it to different type Orange , that is why it is upset and throws Exception.