• Post Reply Bookmark Topic Watch Topic
  • New Topic

Can i have a practical example for down casting in java?  RSS feed

 
jacob deiter
Ranch Hand
Posts: 588
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why down casting is needed in java. Can i have a practical example for down casting in java?. I please do not want an academic example.
 
Campbell Ritchie
Marshal
Posts: 56586
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is something you should avoid; lots of casts means your classes are designed badly. Look at this method, which isn't in the List interface. If you want to use it, you have to do some horrible testing with instanceof to prevent class cast exceptions:-LinkedList doesn't have such a method because the size of a linked list and its capacity are always the same. I shall leave you to work out how to handle such a method in this List implementation.
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The only two things I can think of that I use are casting Object to X in my X.equals(Object) implementation, and casting a Graphics reference to a Graphics2D reference when I'm overriding JComponent.paintComponent(Graphics).
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!