permaculture playing cards
The moose likes Beginning Java and the fly likes Casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Casting" Watch "Casting" New topic


Rajnarayan Deenadayalan

Joined: Dec 16, 2003
Posts: 14
What is meant by upcasting and Downcasting?
please provide a clear solution
Paul Sturrock

Joined: Apr 14, 2004
Posts: 10336

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 ]

JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
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!

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
marc weber

Joined: Aug 31, 2004
Posts: 11343

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
I agree. Here's the link:
subject: Casting
It's not a secret anymore!