• Post Reply Bookmark Topic Watch Topic
  • New Topic

Explicit casting in inheritance tree  RSS feed

 
Ranch Hand
Posts: 153
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose the following:
Book is a subclass of Product

Then follows:

source: Murach's Java SE 6, page 249

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?
 
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 Product might 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.

Winston
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!