Question from Sun ePractice exam for SCJP
Hi All. I抦 preparing to take the SCJP for Java 5 test shortly, and in preparation I am taking one of the Sun ePractice exams for this test. I have run across an answer I don抰 understand and am hoping that someone might help me better understand their explanation. I have included the question and answer below.
Here's where I'm fuzzy: I selected option A, compilation fails, as the answer. As you can see by their answer, option A is, in fact, the correct answer. However, I thought the compilation error would be due to the statement on line 10. The statement on line 10 is attempting to assign a superclass object of type Dog, referenced by d2, to a reference variable for a subclass of Dog, h1 of type Harrier, without an explicit cast. But their answer states that the compilation will fail due to an error on line 8, not line 10. I don抰 understand this. With respect to line 8, I can see that a cast from a subclass to it抯 superclass would make the code more clear, but I don抰 see why the compilation would fail due to no cast on this line. Furthermore, the compilation will certainly fail from the statement on line 10. I ran the code, and it did fail due to line 10. Do you think this is just a mistake in their answer, or am I missing something?
Any insight would be much appreciated.
The question and answer from the practice exam are as follows:
Given:
1. class Dog { }
2. class Harrier extends Dog { }
3.
4. class DogTest {
5.public static void main(String [] args) {
6.Dog d1 = new Dog();
7.Harrier h1 = new Harrier();
8.Dog d2 = h1;
9.Harrier h2 = (Harrier) d2;
10.Harrier h3 = d2;
11.}
12. }
Which is true?
A-Compilation fails
B-Two Dog objects are created
C-Two Harrier objects are created.
D-Three Harrier objects are created
E-An exception is thrown at runtime
Answer:
Option A is correct. The compiler will issue an incompatible types error because of the assignment on line 8.

