I implemented this code:
class A {
//some code
}
class B extends A {
// some code
}
class C {
public static void main(String []args)
{
Following is a compiletime casting -
A a = new B();
Such static castings are implicitly performed by the compiler, because the compiler is aware of the fact that B is-a A.
Following doesn't compile -
B b = new A();
No compiletime casting here because the compiler knows that A is not B.
Following compiles -
B b = (B) new A();
It is a dynamic casting. With (B)
you are telling the compiler explicitly that you want the casting to happen at runtime. And you get a CCE at runtime, when the runtime tries to perform the cast but finds out that it cannot be done and throws a CCE.
When you do (or have to do) something like this, the responsibility falls upon you (not the compiler) to make sure that a CCE doesn't occur at runtime.