I don't understand why it is only ok to explicitly cast a superclass (Product) to a subclass (Book) if the target class is a valid subclass (Book).
If Product is a parent of Book, then why can't a Product object be explicitly cast to a Book object?
Ryan McClain wrote:If Product is a parent of Book, then why can't a Product object be explicitly cast to a Book object?
Because, even though a particular Productmight be a Book, the compiler has no way of knowing whether it IS a Book, because you told it it was a Product.
And Java is compiled. You can get away with that sort of stuff in some late-binding languages or scripts that only care about what the runtime type of the object is; but not in a strictly-typed one like Java.
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here