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
Joined: Mar 02, 2000
Posts: 3143
posted
0
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).]
Pounding at a thick stone wall won't move it, sometimes, you need to step back to see the way around.
Randall Twede
Ranch Hand
Joined: Oct 21, 2000
Posts: 4089
posted
0
Angela, You do? I must just be egomaniac can do no wrong. Is that a common practice in the real world?
SCJP
Frank Carver
Sheriff
Joined: Jan 07, 1999
Posts: 6913
posted
0
I don't think using an exception for this is a good idea. A much more common idiom, is to use instanceof:
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
Joined: Oct 18, 2000
Posts: 10
posted
0
Thanks a lot ! I am clear now .
Angela Poynton
Ranch Hand
Joined: Mar 02, 2000
Posts: 3143
posted
0
Actually I prefer Frank's method ... am going to change ... it'll have to be a 12 step programme.
Cindy Glass
"The Hood"
Sheriff
Joined: Sep 29, 2000
Posts: 8521
posted
0
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
"JavaRanch, where the deer and the Certified play" - David O'Meara