Studying for my OCA Java SE 7 Programmer I exam, so newbie question. I have an example question I do not understand. The following code compiles, but gives a ClassCastException at runtime:
interface Roamable {
}
class Phone {
}
public class Tablet extends Phone implements Roamable {
public static void main(String... args) {
Roamable var = (Roamable) new Phone();
}
}
When I change Roamable var = (Roamable) new Phone();
into Roamable var = (Roamable) new String();
I get a compilation error right away.
Two questions:
- Why does the code above compile at all? Phone seems unrelated to Roamable to me?
- Why does the code compile with
new Phone()
, but doesn't it compile withnew String()
?
final
and hence there's no way that a subclass of String could be Roamable. – Broadbill