|
Re: Upcasting & Downcasting !
|
Posted: Jul 16, 2003 7:50 AM
|
|
> po.x; // The value of x in parent class is called. Why???
Polymorphism doesn't work for variables because late-binding is not possible. The decision which variable to access is based on the compile-time informat and that says: "this is of type Parent"
> po.m; // The m in child is called. Why ???
Here, polymorphism is working because you're calling a method. Decision which method to call is left to the VM which decides at runtime, based on the run-time type of the object stored in the variable.
> co = po; // Can't Do why ???
The compiler can only check information that is available at compile-time and that indicates that po is of type parent (which is not a child). The compiler will therefor refuse this line of code. Instead you have to do 'co = (Child) po', telling the compiler: "I know that po will be of type Child". However, there is the risk that po isn't a child at runtime and this'll result in a ClassCastException.
-Boris
|
|