posted 16 years ago
"Why doesn't the compiler see that o1 ("A") is part of B's inheritance tree?"
Actually it doesn't have much to do with seeing part of the inheritance tree; it's more of a fundamental issue on how you are suppose to use the reference variable.
Let's say we have a parent class named animal and child class named cat.
class animal{}
class cat extends animal{}
cat is a animal but
animal is not a cat!!
so you can have
animal a = new cat();
but not cat c = new animal();
Remember to always have reference variable of something in the high inheritance tree and point to some instance in the equal or lower inheritance tree. When you are trying to point to some instance in the higher inheritance tree, 9 out of 10 times the program will blow up if not in compile time, most likely in run time.
In your case it's actually rare that if you do explicit cast, the program will actually run. But it's very rare to see example like this:
A o1 = new C( );
B o2 = (B)o1;
Because it turned into something like B o2 = new C();
during run time which is permitted.
I was thinking more traditional case where you have:
A o1 = new A();
B o2 = (B)o1;
even though it will compile, during runtime it blows up. Just remember pointing downwards in inheritance tree good, but if try to point upwards, then you are asking for trouble.
[ September 25, 2007: Message edited by: Tony Smith ]
[ September 25, 2007: Message edited by: Tony Smith ]