HI
Im hoping some of you very smart people here can explain what exactly is happening with the following code.
This question is for the OCA
Java 7 exam. It is supposed to be simple enough but Im finding it difficult to understand
the sequence of the code. Here is the code simple enough
Interface I{}
class A implements I()
class B extends A{}
class C extends B{}
The following declarations:
A a = new A();//Easy enough set up in a
test class
B b = new B();//Easy enough set up in a test class
...............................................................................................................................................................
which of the following will compile?
1/ a = (B)(I)b; // Is b cast to I then I cast to B??.....Any Help here please??
2/ B = (B)(I) a; // Is it trying first to cast a to an I ???
3/ A = (I) b;// ???
4/ I = (C) a;// ???
..............................................................................................................................................................................................
There are answers to this question but they do not help in my understanding of the question they are...
a = (B)(I)b;
class B does implement I because it extends A, which implements I. A reference of type I can be cast to any class at compile time.
Since B is-a A, it can be assigned to a.
B = (B)(I) a;
This will fail at run time because a does not point to an object of class B.
A = (I) b;
An I is not an A. Therefore, it will not compile.
I = (C) a;
It will compile because a C is-a A, which is-a I, and a reference of class A can point to an object of class C.
But it will fail at runtime because it does not point to an Object of class C
Any further explanations much appreciated Thanks!