posted 17 years ago
Whether a downcast succeeds at runtime depends on the true runtime type of the object -- that is, what was used with "new."
For example, suppose you have an Animal reference "a." You can satisfy the compiler by explicitly downcasting to type Dog...
Dog d = (Dog)a;
But whether this works at runtime depends on the true runtime type of "a." If you had...
Animal a = new Animal();
...then the true runtime type of "a" is Animal, and a downcast to type Dog will fail because an Animal (the object created) is not really a Dog. On the other hand, if you had...
Animal a = new Dog();
...then a downcast of "a" to type Dog will succeed, because the object referenced by "a" is, in fact, a Dog.
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org