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)"
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"
Applying the rule "no Downcast without prior Upcast" in a trap, the scjp-trappers would have ready for us:
1. Is the ineritance tree ok, if yes proceed, the code compiles, if no=compilation error
2. All upcasts will run ok (Parent=Child), also nonsense casts as in e), a) b) and e) will run
3. Are there any downcasts (Child=Parent)? if yes beware, in c) and d) there are
4. Is there any upcast before the downcast? Has the Child-Constructor ever run before on the parent-reference? If yes ok, if no =>ClassCastException
in c) the foregoing upcast lacks!
oh sorry, it is a ClassCastError as it should be. It is not a compilation error.
I want to have some reliable rules to for the questions "does it compile" or "there is a ClassCastError".
My example should be a recipe how to do that. Here is it again:
a) is the inheritance sequence ok, if yes proceed, if no => compilation error
b) is there any downcasting? no => it should run, yes => proceed
c) is there an upcast on the reference variable which is involved in the downcast? => yes => runs
d) If ther is no preceeding upcast => ClassCastError