Hi Angela,
When casting, you need to keep a few things in mind.
First, the compiler always uses the
declared type of both objects.
Second, a superclass can hold a reference to any of it's subclasses.
In your example, you are casting a 'Super' object 'sup' to a valid subclass of 'Super'. The compiler does not see this as an error since
it's possible 'sup' may actually hold a reference to an object of it's subclass, 'Sub'.
Note that while we can see, by reading the code, that this is not the case, the compiler doesn't. It just knows it's possible the cast is legal and assumes you know what you are doing
At runtime it turns out that the real type of 'sup' is 'Super'. While a 'Sub' is also a 'Super', a 'Super'
is not the same as a 'Sub' so the cast is rejected.
A subclass is, by definition, an extension of a superclass. It contains everything it's superclass does
plus more. Which is why you can always assign a subclass to a superclass reference. The reverse
is not true. A superclass will be missing the 'more' that's defined in the subclass and will therefore
not behave the same as the declared type. It would break the subclass contract.
Hope that helps.
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform