Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting

 
Rajnarayan Deenadayalan
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is meant by upcasting and Downcasting?
please provide a clear solution
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Upcasting is when we handle an object as if it were of its base type, down casting is the opposite. For example:

This defines two classes, one which extends from the other. If I write a program like this:

[ January 19, 2005: Message edited by: Paul Sturrock ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Upcasting is always safe - the compiler will tell you if it's not. Something as simple as:

creates a real ArrayList but references it as a List. This is actually a pretty good idea as long as none of the later code needs methods that are on ArrayList but not on List.

A down cast might or might not work. At runtime it might throw an exception.

The parameter passed to this method must be a List. It might or might not be an ArrayList. If I'm real sure it's an ArrayList I can try to cast it to ArrayList as shown, but I'd be smart to remember it might not work.

Casting is very common with collections. If I know my Map only contains Widgets, I can write this:

But I run the risk of an exception if some other type of object gets into the list!
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic