|
JVM performs stricter checks at the runtime. These runtime checks are required as often the compiler may not know all facts at compile time. It may allow casting which is not actually possible to perform (For instance casting between Date and Auditable). Therefore, Java does this second level check at runtime to see whether the proposed cast in the code is actually possible. The following runtime checks are performed:
If you are casting one class-type to a new class-type, the new class-type must be a superclass of it.
If you are casting one class-type to an interface-type, then that interface must be the implemented by the class.
These runtime checks may sound familiar, as they are the same rules as the rules of reference conversion. The runtime check ensures that object reference is cast in such a way that the object it refers will be treated properly. For instance, a CheckingAccount is also an Account, it can perform all methods of Account class (as it inherits it). Therefore following cast is ok at runtime as well:

On the other hand, an Account is not a CheckingAccount, therefore it should not be treated as CheckingAccount. But the compile-time checks allows you to cast it as:

The reference acc will point to an Account object at runtime. However, since it is cast to CheckingAccount, you might write a code calling methods of CheckingAccount on it. But the Account object do not have any implementation of such methods. To avoid these kinds of potential problems at runtime, Java performs a runtime check right at the time of casting. It checks whether acc is pointing to an object that can be treated as CheckingAccount. In the above example, it is not. Therefore, Java throws a runtime exception ClassCastException at the illegal cast.
|
|
JVM throws the ClassCastException to indicate that the code has attempted an illegal cast. |