Terence Gronowski wrote:When is there a ClassCastError or a CompilationError? Are there some rules? Are there some more cases as I list below?
Hi Terence, please refer to this
thread for casting rules: -
webpage
If I have two sibling objects (objects with the same parent) as in #1 there is a compilation error, this means, that the compiler can foresee that something is wrong.
if you apply referencing rule here. ("A reference of type X can point to objects of class X, or to objects of any of X's subtypes. "
then this can be true
now downcasting is required when you assign "reference of type B" (e.g B b) to a "reference that is supertype of B" (e.g a)"
i.e.
and in your case d2 is not a supertype of d1!
It is somehow clear for me, that you cannot cast a Double into a String, but what is the cue behind this?
That is again referencing rule - "if the object pointed to by the reference on right hand side(e.g a) is not assignment compatible with the reference type you are assigning to (e.g b) according to the referencing rule, a ClassCastException will be issued at run time"
and the complete (compiled code) is
I hope this would help..