• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Casting

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What is meant by upcasting and Downcasting?
please provide a clear solution
 
Bartender
Posts: 10336
Hibernate Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
 
I child proofed my house but they still get in. Distract them with this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic