• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can we really downcast in Java - urgent

 
ms
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all ,
Can you please tell me that can we downcast in Java or it always throws the ClassCastException .
If it does can you please suggest the appropriate code for that .

Shall be extremely thankful !
 
Angela Poynton
Ranch Hand
Posts: 3143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A ClassCastException will only be thrown if you downcast an object to the wrong type (e.g. You have a String which is currently stored as type Object ... and you downcast it to an Integer by mistake.) ... I always downcast within a try/catch block and catch the exception .. just in case!
Almost always you will be sure what the actual type of the object is so the exception is very rarely thrown!

PS. We have a naming convention here at Javaranch can you please read this http://www.javaranch.com/name.jsp and re-register with an appropriate name.

[This message has been edited by Angela Poynton (edited March 20, 2001).]
 
Randall Twede
Ranch Hand
Posts: 4439
3
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Angela,
You do? I must just be egomaniac can do no wrong. Is that a common practice in the real world?
 
Frank Carver
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think using an exception for this is a good idea. A much more common idiom, is to use instanceof:

 
Neel D
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Good Example Sheriff. Just happened to go thru this one.
Neel

[This message has been edited by Neel D (edited March 20, 2001).]
 
ms
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot ! I am clear now .
 
Angela Poynton
Ranch Hand
Posts: 3143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually I prefer Frank's method ... am going to change ... it'll have to be a 12 step programme.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ms,
Please change your name to be compliant with JavaRanch's naming policy.
Your ID should be 2 separate names with more than 1 letter each. We really want this to be a professional forum and would prefer that you use your REAL name.
Thanks,
Cindy
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic