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.
Yes this code should give a runtime error at line 3 because .. A super class cannot be casted to a sub class as it doesnt know anything about it's subclasses. It should give a ClassCastException at runtime.
It's something like this all 'Strings' are Object but vice versa is not true.
What error are you getting at compile time? [ October 19, 2005: Message edited by: Srinivasa Raghavan ]
In the first code above, the flow goes as follows: s1 is pointing to a Sub object, s1 reference is assigned to Base reference base at line 3 which means that base reference is also pointing to the same Sub object as s1. So, line 4 is legal as we can cast a superclass reference to subclass if the superclass reference is actually poiting to a subclass object.
Now, watch the secod code:
Here base refers to Base object. So, when you cast a superclass reference to a subclass reference you will get a runtime error. Hope this helps. But, I am still not sure how there is compile error in the first example. I compiled it and did not get any error. Are you sure there is no typo?