File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes What is upcasing and downcasting ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "What is upcasing and downcasting ?" Watch "What is upcasing and downcasting ?" New topic

What is upcasing and downcasting ?

Parag Patankar

Joined: Feb 26, 2007
Posts: 13

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
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46349
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

Joined: Jan 09, 2008
Posts: 525
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


I agree. Here's the link:
subject: What is upcasing and downcasting ?
It's not a secret anymore!