wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Down Casting to subtype Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Down Casting to subtype" Watch "Down Casting to subtype" New topic
Author

Down Casting to subtype

Srinivas Katta
Ranch Hand

Joined: Feb 01, 2007
Posts: 76
I have executed the below Program and getting ClassCastException at Line Marked as Line 10



My Assumption is Redwood is a Tree and we can downcast Tree to Redwood at Line 10
Deepak Bala
Bartender

Joined: Feb 24, 2006
Posts: 6661
    
    5

Looking for this ? -> http://www.coderanch.com/t/500236/java-programmer-SCJP/certification/casting

Do search our forum before you make a new post


SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
Sahil Kapoor
Ranch Hand

Joined: Sep 12, 2009
Posts: 316
Srinivas Katta wrote:I have executed the below Program and getting ClassCastException at Line Marked as Line 10



My Assumption is Redwood is a Tree and we can downcast Tree to Redwood at Line 10



Dear your assumption is partially true

if tree reference variable is pointing to Redwood object , then only you can Downcast.

At runtime, when JVM tries to downcast object referenced by t1 ( which is pointing to tree object) , it generats ClassCastException because you cannot have Redwood Reference pointing to
a tree object. Why this is not allowed is indeed simple to think. Down the inheritance tree ,, you make you classes specialised , may be by overriding and adding new methods. So if subtype reference points to supertype object , how would you call subtype new specialised methods ??? Tree object does not have any idea , how to behave ???

Thanks !!!

SCJP 6.0 96%

(Connecting the Dots ....)
Harshit Sethi
Ranch Hand

Joined: Jul 16, 2010
Posts: 75
Hello friend, i think the problem is that you are casting object of tree into Redwood ,thats not possible .Downcasting doesn't mean that you can cast any super calss object into sub class.

Read it carefully:
Downcasting is the casting of super class' reference variable which refers to sub class object into the Sub class reference variable.the reference of super class is casted in downcasting if and only if the object referred to by that reference passes the IS-A test for the class of the reference variable in which you are casting.

you have to be sure of that by using instanceof operator.
I hope that helps.Thats all what i know about downcasting.

Regards.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Down Casting to subtype
 
Similar Threads
Please explain DownCast Code from K&B
Casting
Java Casting issue
Overloading and casting
A doubt in the type casting