This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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 ???
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.