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

What is upcasing and downcasting ?

 
Parag Patankar
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • 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
 
Campbell Ritchie
Sheriff
Posts: 48396
56
  • Mark post as helpful
  • send pies
  • 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.
 
Jim Hoglund
Ranch Hand
Posts: 525
  • Mark post as helpful
  • send pies
  • 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...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic