1.public class ClassCastTest {
2.public static void main(
String args[]){
3.A[] a,a1;
4.B[] b;
5.a = new A[10];
6.a1 = a;
7.b = new B[20];
8.a = b;
9.b = (B[])a;
10.b = (B[])a1;
11.}
12. }
class A{}
class B extends A{}
hi mark, here�s the explanation
Line 10 gives a class cast exception. Now lets see how and why-
The theme of the question is �object reference concersion and casting�, While answering such questions keep in mind a basic thumb rule �
NewType=OldType ; //Thumb rule- for conversion to be legal, �OldType� should be a subclass of
//NewType
Line 6 is fine because both a1 and a are references of the same class.
Line 8 is fine because b (an array reference variable) is reference of class B which is a subclass of class A
So this is fine as per the above thumb rule
Lines 9 and 10 have explicit cast used. Another thing that one should remember is that whenever one sees an explicit cast, one must do the following two checks in mind(in fact the compiler checks like this)-
1)Comile time check- check whether the reference on either side (right/left) is a subclass of that on
another side. At lines 9 and 10, above this condition is satisifed get any compiler error Since you
are casting a reference of a superclass into a reference of a subclass, the explicit cast is
necessary
2)Run time check � here you need to determine the runtime classes of references on both sides
For line 9, class of �a� is B (due to line 8). So line 8 is just casting a reference of class B to a refernce �b� ( which is again an objec reference of class B). This in O.K
But at line 10, run time class of �a1� is class A, whereas runtime class of �b� is B. Thus irrespective of the cast, assignment on line 10 is something like this �
Baseclass=superclass,
i.e. the purpose of using a cast has gone in vain.
Hence we get a runtime exception
Hope you got it. CORRECT ME IF I AM WRONG ANYWHERE.