Hi,
From Mala Gupta's study guide for
OCAJP 8, page 624:
ME-Q59) Given the following code, which option, if used to replace //INSERT CODE
HERE, will enable a reference variable of type Roamable to refer to an object of the
Phone class? (Select 1 option.)
Possible answers:
a Roamable var = new Phone();
b Roamable var = (Roamable)Phone();
c Roamable var = (Roamable)new Phone();
d Because the interface Roamable and the class Phone are unrelated, a reference
variable of the type Roamable can’t refer to an object of the class Phone.
Answer: c
Explanation: Option (a) is incorrect. Without explicit casting, a reference variable of
type Roamable can’t refer to an object of the class Phone.
Option (b) is incorrect because this is an invalid line of code that will fail to compile.
Option (d) is incorrect because a reference variable of the type Roamable can refer
to an object of the class Phone with an explicit cast.
Note that although option (c) will compile, it will throw a ClassCastException if
it’s executed.
I don't see how the answer is c and not d. First of all, the explanation says d is incorrect because it is possible to create a reference variable that refers to an object of the class Phone without an explicit cast, but when I do so, I get the following error:
Tablet.java:4: error: incompatible types: Phone cannot be converted to Roamable
Roamable var = new Phone();
^
1 error
Also, how is c the correct answer? The question is what line will enable a reference variable of Roamable to refer to an object of Phone, but since this line throws a ClassCastException, how does that satisfy the condition stated in the question?
Thanks for your help!
Regards,
Shane