When you encounter such code it's advised to replace A,B and C with real-life things to help understand the relationships among them. I choose that A is
Fruit, B is Orange and C is Apple.
Now let's show the relationships: We have that an Orange is a Fruit and an Apple is a Fruit as well.
We create one instance of each, i.e. we have one Fruit instance, one Orange instance and one Apple instance.
Let's look at the different options we have:
1. x=y means that you want to reference an Orange instance with a Fruit reference which is perfectly legal since an Orange is_a Fruit. No runtime exception here.
2. z=x means that you want to reference a Fruit instance with a Apple reference. This will result in a compile-time error since without explicitely casting x to Apple it is not possible and moreover x has to reference an Apple beforehand.
3. y=(Orange)x means that you want your Fruit instance (x) look like it is a Orange and reference it with a variable of type Orange. Well, this will work only if x already references an Orange instance which may not be the case since x may as well reference an Apple instance and you cannot make a Apple look like an Orange. In this case, x references a Fruit and not an Orange. The cast allows to go through compilation without error but at compile time a ClassCastException will be thrown since a Fruit cannot be cast to an Orange.
4. z=(Apple)y means that you want your Orange instance (y) look like it is an Apple and that's is clearly impossible since an Apple and an Orange are not related. This results in a compilation error.
5. y=(Fruit)y means that you want your Orange instance look like it is a Fruit and reference it with a variable of type Orange. The rigth part is not the problem but the result of casting y to Fruit results in y being of type Fruit. Then you want to reference it with a variable of type Orange, which is not permitted by the compiler and results in a compile time error.
HIH
------------------
Valentin Crettaz
Sun Certified Programmer for
Java 2 Platform