java.lang.ClassCastException at runtime or compile time

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!

Jon Skeet
people
quotationmark

Or does the compiler knows only the type of the reference, not of the object (in the memory) itselfs?

It only knows the type of the expression that you're trying to cast. That expression is of type Object, so it's fine to cast it to C as far as the compiler is concerned. While the language could have been designed to let this mistake be caught at compile-time, pinning down the precise semantics of what the compiler has to infer and what it can't infer would be hairy... and you really don't want code that some compilers allow and some don't.

This would fail at compile-time though:

String s = "";
C c = (C) s; // Can't possibly be true

people

See more on this question at Stackoverflow