I have a question regarding Object type casting.
Suppose we have:
A a = new A();
Object o = a;
As I know, what happens behind is that the compiler will copy the address of a and store in the memory area of o variable. Then,we can say that a and o are referencing to the same object.
If we do something like this:
String s = "abc";
int a = (int)s;
Then I understand that the compiler cannot copy the string value to the int memory area.
But if we have:
A a = new A();
B b = (B)a;
This might be ok at the compile time. However, a run time error may happen which is something like “cannot casting….”.
So, I dont understand what actually happen in memory that makes the above casting cannot be performed. Is it just copying the address of a to the memory area of b? If so, why it is not possible?
Or it will copy all the members of A to replace all the members of B?
Thanks
The compiler does Static Type Checking meaning that if A and B do not belong to the same inheritance hierarchy, it would not allow a cast to happen between the two.
Think about it, if they are not belong to the same hierarchy, even if compiler lets you cast an object of A to a type of B, since A does not inherit from B or its inheritors, you might want to invoke one of the methods of type B on the casted object and it will fail miserably at runtime.
There is an interesting point exist here though, if B is an interface, the compiler would let the cast to happen even if they do not belong to the same inheritance tree:
The reason for that is because A might be from a different hierarchy tree but there is still possible that A or one of its Base classes have implemented B so you might have a point by that cast and compiler would let that.