2. is implicit upcasting. 3. is explicit downcasting with no error. 4. is implicit upcasting.
The problem is 1. You are doing explicit downcasting, so it will compile fine, but at runtime the JVM will realize that reference a actually doesn't point to a BB object, so a ClassCastException will be thrown.
The difference between 1. and 3. is that in 1., the a reference points to an AA object, which is not a BB object, so it is a runtime error. However, 3. works fine because reference c, which is of type AA, actually points to a BB object. [ December 23, 2008: Message edited by: Ruben Soto ]
All code in my posts, unless a source is explicitly mentioned, is my own.
Joined: Jul 11, 2005
Thanks for the clarification!!! Its helpful indeed.
Whenever there is explicit downcasting one needs to makes sure if the Superclass ref_variable referencing to the Subclass object.
But it's not necessary that the Superclass ref_variable references a Subclass object, it could also refer to an object of any of the Subclass' subclasses. The object it references simply needs to pass the Is-A test for the subclass type.