posted 22 years ago
Rick :
When you are casting objects up and down the hierarchy, the compiler strictly looks at the type of the reference variable and not the actual object to which the reference variable is pointing. A reference variable of FourWheeler type can certainly be pointing to an object of Car type ( as illustrated by the new line you added ). In such a case at runtime, the cast is valid and program will continue to execute.
However, a reference variable of FourWheeler type can also point to an object of Truck or Crane type. The compiler does not know that, so compilation will proceed. At runtime, the reference variable points to an object that is not compatible with the left hand side variable of the assignment operator(=). Therefore you get the class cast exception.
Please remember the distinction between the type of the reference variable and the actual type of the object that it points to.
HTH