I've just read in an OCA-Book (Oracle Certified Associate), that:
"Some casts exceptions can be detected as errors at compile-time, but others can only be detected at runtime".
Now I am trying to find an example for both cases: compile-time and runtime.
Consider the following class structure:
class A {}
class B extends A {}
class C extends B {}
The following cast
Object o = new C();
B b = (B) o;
is correct. So the code would run without a ClassCastException
.
The cast
Object o = new B();
C c = (C) o;
is wrong. The Object o
is at least of the type B
; so it could be cast to B
or A
.
But could be this detected at runtime or compile-time? I would guess at compile-time?! Or does the compiler knows only the type of the reference, not of the object (in the memory) itselfs? If this is true, the compiler could not decide if the cast is correct or not at compile-time.
Thank you for your help!