So I was studying some OCAJP JAVA sample questions, and I stumbled on the following question.
Consider following code.
interface I{ }
class A implements I{ }
class B extends A { }
class C extends B{ }
And the following declarations:
A a = new A();
B b = new B();
which will compile and run without error?
A. a = (B)(I)b;
B. b = (B)(I) a;
C. a = (I) b;
D. I i = (C) a;
the answer to the problem was A. Which makes sense. What I don't understand though is that B. wasn't the correct answer. It said it was incorrect choice because "This will fail at run time because a does not point to an object of class B."
Now, I actually went to Eclipse and wrote down the entire code. C obviously didn't compile and D. failed at run time. B. compiled without issue at least with my code. Am I missing something here? or is the book actually wrong? The code that I actually put into Eclipse was this:
public class Test{
public static void main (String[]args){
A a = new A();
B b = new B();
a=(B)(I)b;
b=(B)(I)a;
}
}
interface I{ }
class A implements I{ }
class B extends A { }
class C extends B{ }