During compile time the compiler looks if everything related to casting is ok by taking the reference variables. The code is fine, because B IS-A A and in main an explicit cast is done in order to tell this to the compiler:
During runtime though you get the ClassCastException, because Type A is the super class of type B, so an instance of type A cannot be converted to the type of the subclass B.
When you say that one class extends another class, you can say that the subclass "is a" type of the superclass. Look at this example:
In this case, the class Cat extends the class Animal. Therefore, we can say that a Cat "is a" type of Animal. Likewise, Dog extends Animal so we can say that a Dog "is a" type of Animal. We say this because, through inheritance, Cat and Dog take on all of the aspects of an Animal. In addition, however, both Cat and Dog define some extra details about themselves that the generic Animal class does not have. Therefore, an Animal "is not a" Cat and an Animal "is not a" Dog. Similarly, Cat and Dog have no such relationship. They are "sibling" classes. A Cat "is not a" Dog and a Dog "is not a" Cat.
You get a ClassCastException when you attempt to cast an object as something that it "is not." For example, you can safely cast a Cat as an Animal because a Cat "is a" type of Animal. However, if you try to cast a Dog as a Cat, you get a ClassCastException because a Dog "is not a" Cat. Here's an example:
You get a ClassCastException when you attempt to cast an object as something that it "is not." For example, you can safely cast a Cat as an Animal because a Cat "is a" type of Animal. However, if you try to cast a Dog as a Cat, you get a ClassCastException because a Dog "is not a" Cat.
Suppose it does not cause the class cast exception at runtime what will happen?
B instances can have additional members(fields and methods) than A instances.
b is a reference of type B.
You as a programmer if given b as a handle will try to access the extra members found only in B.
But since b is actually pointing to an A instance which does not have those members you will get a meltdown when u try to use members that dont exist. For this one reason alone there should be the class cast exception to avoid potential "method/fields not found in object" exceptions.
If you follow the same line of thinking for the following code it can never cause the same problems because A will always have less members than B and all members of A will be in B for sure.
[ June 10, 2004: Message edited by: Swamy Nathan ]