When can a certain object be cast into another object? Does the casted object have to be a subtype of the other object? I\'m trying to figure out the rules...
Suppose we want to cast d object to A,
A a = (C)d;
So internally 3 rules have been checked by Compiler and JVM. The compiler is checking first 2 rules at Compile time and JVM will check last one rule at Runtime.
Rule 1 (Compile time checking):
Type of 'd' and C must have some relation (child to parent or parent to child or same time).If there is no relationship then we will get a compile error(inconvertible types).
Rule 2 (Compile time checking):
'C' must be either same type or derived type(subclass) of 'A' otherwise we will get a compile error(incompatible types).
Rule 3 (Runtime Exception):
Runtime object type of 'd' must be same or derived a type of 'C' otherwise we will get a runtime exception (ClassCastException Exception).
Find following examples to get more idea,
String s = new String("hello"); StringBuffer sb = (StringBuffer)s; // Compile error : Invertible types because there is no relationship between.
Object o = new String("hello"); StringBuffer sb = (String)o; // Compile error : Incompatible types because String is not child class of StringBuffer.
Object o = new String("hello"); StringBuffer sb = (StringBuffer)o; // Runtime Exception : ClassCastException because 'o' is string type and trying to cast into StingBuffer and there is no relationship between String and StringBuffer.