This is something that a friend brought to me out of a Java book. It’s an interesting question that appears subtle at first but it’s obvious (I think) when you think about what’s really going on in the context of OO. I’ve seen this question also on BrainBench tests. It may even come up in an interview – trust me.
The question goes something like this.
"The below will compile but will give a runtime casting error. Why? Assume that class MyDerived is derived from class MyBase."
MyBase theBase = new MyBase();
MyDerived theDerived = (MyDerived)theBase;
Give up?
The reason is because while MyDerived "isa" MyBase, the reverse isn’t true -- MyBase "isn’t" MyDerived.
If you try to do the opposite -- cast theDerived into an object of type MyBase -- that will work. This is because, due to the inherited relationship of MyDerived from MyBase, theDerived contains within it methods and data members that conform fully to the definition of MyBase.
The reverse is not true. If you try to cast theBase into an object of type MyDerived, this will NOT work. This is because theBase does not contain within it ANY of the methods or data members that make MyDerived different from MyBase. Since those members are missing, there’s no way to successfully cast an object of type MyBase to a variable of type MyDerived. Hence the invalid-cast exception.