• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Down Casting to subtype

 
Srinivas Katta
Ranch Hand
Posts: 76
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Looking for this ? -> http://www.coderanch.com/t/500236/java-programmer-SCJP/certification/casting

Do search our forum before you make a new post
 
Sahil Kapoor
Ranch Hand
Posts: 316
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 !!!
 
Harshit Sethi
Ranch Hand
Posts: 75
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic