posted 24 years ago
1. Object obj = aDer;
2. Runnable rn = (Runnable)obj;//line1.....OK
3. Observer ob = (Observer)obj;//line2.....OK
4. ApBase ap = (ApBase)obj; //line3.....OK
5. Object obj = aBase;
6. Runnable rn = (Runnable)obj; //line1....OK
7. Observer ob = (Observer)obj; //line2....NOT OK
8. ApDerived apd = (ApDerived)obj; //line3....NOT OK
Object
|
|
ApBase .... Runnable
|
|
ApDerived ...... Observer + Runnable (being subclass of ApBase)
Symbols: "|" - extends "...." implements
Casting is all about looking "UP" in hierarcy.
Line 2,3,4 are having an instance of Apderived, looking for casting: Runnable,Observer, and ApBase, all up in hierarcy. Apderived instance is all these things, so castable.
Line 7,8 are having an instance of ApBase, looking for casting Observer, and ApDerived, all down in hierarcy. ApBase instance is not all these things. It inherits what's all is above or what all it is, not below it!
I think you wouldn't get any compile error. But surely runtime error.
Please correct me if i am wrong !