• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

What is upcasing and downcasting ?

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

Just want to know what is upcasting and downcasting concept in JAVA ? I read it in a book "thinking in java", but not very clear to me.

pl explain.

thanks & regards
parag
 
Marshal
Posts: 80639
471
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Kind of class-casting.
If you up-cast it is casting towards the superclass. This is always safe; you can always cast a String to an Object or an ArrayList to List or Serializable. It is also never necessary. You can always assign a String object to an Object reference without a cast.

If you down-cast it is casting towards the subclass. This is always necessary if you want to assign a superclass object to a subclass reference. It is never safe; if you try to cast a Vehicle object to a Car reference when it is actually a Van or a Bus, you will suffer a ClassCastException. The idea behind generics is to avoid down-casting.
 
Ranch Hand
Posts: 525
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Up-casting is often useful, and down-casting is allowed by the
compiler, but can be dangerous at run time.

Now, what is casting? You cast an object when you want to treat
it as a different type - very helpful at times. For example, consider
javaBook, an object of type JavaBook (JavaBook extends Book).
If my interest is the numberOfPages in javaBook, it can be up-casted
to class Book with confidence.

Book temp1 = (Book)javaBook; // up-cast is quite safe
int pageCount = temp1.getPages();[/code]

Starting with a simple Book object, myBook, however, and looking for
its chapter on JVM doesn't work so well because it doesn't have one.

JavaBook temp2 = (JavaBook)myBook; // down-cast is allowed but
int jvmChapter = temp2.getJvmChapter(); // run-time error on cast

Jim...
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic