Hi everybody,
I've just joined the group. Let me see if I can crack this.
At compile time errors are thrown due to incompatibility b/w reference types and run time the errors are due to the actual object types.
10.z = x;
z is a subclass of x and hence x cannot be assigned to z without a specific cast (i.e z = (C)x)
11.y = (B)x;
Explicit casting has been done here, it compiles.
But since x denotes a object of type A, and not of B or its subclass a ClassCast exception will be thrown.
So line 10 throws a compile time error because
12.z = (C)y;
B and C are two unrelated classes. For casting to be legal(class1 must be derived from class2 or viceversa)
Hence the compile time exception.
13.y = (A)y;
Here the cast( (A)y) is legal since B is a subclass of A). However you are now trying to assign the result of this cast( class A) to a reference of type B and hence a compile time exception.
Hope thats clear.
Shankar.
1.class A {}
2.class B extends A {}
3.class C extends A {}
4.public class Q3ae4 {
5. public static void main(String args[]) {
6. A x = new A();
7. B y = new B();
8. C z = new C();
9.x = y;
10.z = x;
11.y = (B)x;
12.z = (C)y;
13.y = (A)y;
14. }
15.}
Originally posted by Jaikumar Nair:
I have a doubt regarding the following code:
1.class A {}
2.class B extends A {}
3.class C extends A {}
4.public class Q3ae4 {
5. public static void main(String args[]) {
6. A x = new A();
7. B y = new B();
8. C z = new C();
9.x = y;
10.z = x;
11.y = (B)x;
12.z = (C)y;
13.y = (A)y;
14. }
15.}
Why does line 11 give only run-time error and not compile time error? and lines 12 & 13 give compile time error. I am a bit confused with this example. Could someone please explain?
JAI