• Post Reply Bookmark Topic Watch Topic
  • New Topic

Downcasting  RSS feed

 
kri shan
Ranch Hand
Posts: 1489
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Getting ClassCastException in B b = (B) a;.


 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's right. a isn't a B, so it can't be cast as one.
 
kri shan
Ranch Hand
Posts: 1489
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can i try like this ?


 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No. Adding member variables won't change the fact that a is not a B. If you want a to be a B, then you need to create it as a B.

By the way, A and B are terrible choices. Why not Animal and Baboon? That'd make more sense, no?
 
kri shan
Ranch Hand
Posts: 1489
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you need to create it as a B.

Are you referring the constructor ?
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, if you want an instance of a specific type, you have to use the constructor of that type, or the constructor of one of its sub-classes.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!