• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Rob Spoor
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Carey Brown
Bartenders:

Explicit casting in inheritance tree

 
Ranch Hand
Posts: 153
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic